AngularJS学习笔记二

指令

1、restrict:指令声明四种表现形式:A(属性)、C(类)、E(元素)、M(注释),使用“restrict”来进行配置。

2、template:指令中生成的字符串html模版

3、templateUrl:模版的地址

4、replace:将原指令所在标签替换为模版内容时,是否保存原指令html,为false时则将模版中内容插入原指令标签中。

5、transclude:将原指令中间的内容移动到template中有“ng-transclude”指令所属标签位置,为true时,覆盖模版中标签,为false时,不覆盖并且原指令中间内容丢弃。

6、scope:指令的作用域,有三种作用域表示方式:

  ① scope : { innerArgs : "args" } 独立的指令作用域,不能获取到父作用域。

  ② scope : false 继承自父作用域。

  ③ scope : {

      "argument1" : "@attribute",  //将指令内部属性与作用域变量进行单向绑定

      "argument2" : "=attribute",  //将指令内部属性与作用域变量进行双向绑定

      "argument3" : "&func"    //将表达式与作用域变量进行绑定

    }

7、compile:进行dom操作与处理。

8、link:在指令内部进行元素的事件绑定与数据绑定。

9、controller:将指令中方法暴露给外部其他指令使用。

10、require:依赖于其他的指令名称,用法: require : "^otherDirective"

应用:

<div ng-app="app">
    <div ng-controller="demoCtrl">
        <hello toname="elic" hi>这是指令中原来的内容</hello>
        <div hello toname="elic">这是指令中原来的内容</div>
        <div class="hello" toname="elic">这是指令中原来的内容</div>
    </div>
</div>
<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
    var app = angular.module("app", []);
    app.directive("hello", function () {
        return {
            restrict: "ACE",
            template: '<div>Hello,How are you? <span ng-transclude>此内容被原指令中内容覆盖</span></div>',
            transclude: false,   //将原指令中间的内容嵌入到template中有“ng-transclude”指令的html中
            //为false时,丢失原指令中内容,模版中内容正常显示
            controller: function ($scope) {
                $scope.userName = "";
                this.say = function () {
                    alert("hello指令调用:" + $scope.userName);
                }
                this.setName = function (name) {
                    $scope.userName = name;
                }
            },
            link: function (scope, element, attrs) {    //参数顺序不可乱,但名称可自定义
                var userName = attrs.toname;    //标签中定义的属性为“toName”,但此处取属性也要全部使用小写
                //scope.sayHello(userName);     //调用作用域中的方法
                scope.$apply();         //第一次调用会报“$apply already in progress”错误,不知道原因……
                scope.$apply("sayHello('" + userName + "')");   //第二次调用成功

                //element为angular包装集
                element.bind("click", function () {
                    alert(userName);
                });
            }
        };
    });

    app.directive("hi", function () {
        return {
            require: "^hello",  //依赖于“hello”指令
            //通过第四个参数,自动注入“hello”指令中的controller,名字可自定义
            link: function (scope, element, attrs, helloCtrl) {
                helloCtrl.setName("demo");
                helloCtrl.say();
            }
        };
    });

    app.controller("demoCtrl", function ($scope) {
        $scope.sayHello = function (userName) {
            alert("Hello," + userName);
        }
    });
</script>
原文地址:https://www.cnblogs.com/elic/p/4066240.html