理解指令的restrict属性

restrcit属性说明

restrict: EACM中的任意一个之母。它是用来限制指令的声明格式的。

E - 元素名称:<my-directive></my-directive>
A - 属性: <div my-directive="exp"> </div>
C - 类名:<div class="my-directive: exp;"></div>
M - 注释: <!-- directive: my-directive exp -->

它做了什么

示例

<html ng-app='app'>
<body>
    <hello> </hello>
    <div hello> </div>
    <div class="hello"> </div>
    <!-- directive: hello -->
</body>
<script src="bower_components/angular/angular.js"></script>
<script>
var appModule = angular.module('app', []);
appModule.directive('hello', function() {
    return {
        restrict: 'AEC',
        template: '<h3>Hi there</h3>',
        replace: true
        link:function(scope, elem, attrs){
            console.log(elem);
            //console.log(attrs);
        }
    };
});
</script>
</html>

运行结果

<h3>Hi there</h3>
<h3 hello>Hi there</h3>
<h3 class="hello">Hi there</h3>
<h3>Hi there</h3>

可以看到几种方式,做的事情一样,只有部分地方不同. 这些区别有什么作用?

有何作用 

restrict=E时,浏览器无法识别指令的声明元素,则这个指令一定是起替换作用,也就是说template一定有值.

restrict=A时,它是以元素属性存在的,那么这个指令的作用可以不是替换. 那么它可以做什么?以link方式操作dom.

比如在初始时为元素聚焦

<input type="input" focus/>
appModule.directive('focus', function() {
    return {
        restrict: 'A',
        link:function(scope, elem, attrs){
            $(elem).focus();
        }
    };
});

restrict=C,则是在绑定指令的同时,指定它的css样式,让指令与样式同步.

restrict=M,则在一些场合非常有用,方便在注释与代码之间切换.


转载于:https://my.oschina.net/yongqing/blog/296255

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值