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,则在一些场合非常有用,方便在注释与代码之间切换.

  • 相关阅读:
    va_list/va_start/va_arg/va_end深入分析【转】
    Linux Kernel中断子系统来龙去脉浅析【转】
    Linux系统调用---同步IO: sync、fsync与fdatasync【转】
    Linux中变量#,#,@,0,0,1,2,2,*,$$,$?的含义【转】
    linux下的module_param()解释【转】
    Makefile 使用总结【转】
    FLASH的知识【转】
    Linux MTD系统剖析【转】
    linux的mtd架构分析【转】
    linux设备树笔记__dts基本概念及语法【转】
  • 原文地址:https://www.cnblogs.com/boshen-hzb/p/6019406.html
Copyright © 2011-2022 走看看