理解指令的restrict属性

restrcit属性说明

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

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

它作了什么

示例html

<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>

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

有何做用 
dom

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

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

好比在初始时为元素聚焦code

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

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

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

相关文章
相关标签/搜索