欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 综合教程 >内容正文

综合教程

理解指令的restrict属性(转)

发布时间:2023/12/15 综合教程 51 生活家
生活随笔 收集整理的这篇文章主要介绍了 理解指令的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,则在一些场合非常有用,方便在注释与代码之间切换.

总结

以上是生活随笔为你收集整理的理解指令的restrict属性(转)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。