zoukankan      html  css  js  c++  java
  • 理解指令的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,则在一些场合非常有用,方便在注释与代码之间切换.

  • 相关阅读:
    MinGW-编译器
    Enum , Enum Class ?
    C++编译器之间的不同性能
    交叉验证
    经验风险最小化-结构风险最小化
    图像卷积
    pytorch官网上两个例程
    ORB feature(O for orientation)
    Catalan数
    无责任共享 Coursera、Udacity 等课程视频(转载)
  • 原文地址:https://www.cnblogs.com/boshen-hzb/p/6019406.html
Copyright © 2011-2022 走看看