• angular指令中的scope绑定策略


    针对独立 scope,可以通过在对象中声明如何从外部传入参数。有以下三种绑定策略:

    @ - 使用 DOM 属性值单项绑定到指令 scope 中。此时绑定的值总是一个字符串,因为 DOM 的属性值是一个字符串。

    <div my-directive age="26"></div>
    
    scope: {
        age: '@'
    }

    = - 在父 scope 和指令 scope 之间建立双向绑定。

    <div my-directive age="age"></div>
    
    scope: {
        age: '='
    }

    & - 使用父 scope 的上下文执行函数。一般用于绑定函数。

    <div my-directive sayHi="sayHi()"></div>
    
    scope: {
        sayHi: '&'
    }

    绑定函数时,有时需要向指令外部传递参数,如下:

    app.controller('myCtrl', [
        '$scope',
        '$cookieStore',
        function ($scope, $cookieStore) {
            $scope.name = 'Heron';
    
            $scope.sayHi = function (name, age) {
                alert('Hello ' + name + ', your age is ' + age);
            };
        }
    ]);
    
    app.directive('myDirective', [
        function () {
            return {
                restrict: 'E',
                replace: true,
                scope: {
                    clickMe: '&'
                },
                template: 
                    '<div>
                        <button class="btn btn-info" ng-click="clickMe({ age: age })">点我</button>
                    </div>',
                link: function (scope) {
                    scope.age = 26;
                }
            };
        }
    ]);
    <div ng-controller="myCtrl">
        <my-directive click-me="sayHi(name, age)"></my-directive>
    </div>

    说明一下:首先声明 clickMe: '&' 使用父 scope 的环境执行 clickMe 函数,然后在传递给指令时声明 click-me="sayHi(name, age)",表示父 scope 的 sayHi 方法需要两个参数,一个是 name,一个是 age,然后再指令中使用对象 {} 的方式向外传递参数,如 ng-click="clickMe({ age: age })",表示向指令外传递 age 参数,sayHi 方法从指令拿到 age 参数,再从自己的上下文中拿到 name 参数。

  • 相关阅读:
    一个很好的菜单源码
    在盗版xp下安装ie7正式版 
    [导入]买新手机了
    [导入]手机解锁全集
    12种找工作方式的成功率
    Kerberos的原理 3
    Kerberos的原理 4
    Kerberos的原理 1
    jQuery 原理的模拟代码 6 代码下载
    Hashtable 中的键值修改问题
  • 原文地址:https://www.cnblogs.com/gongshunkai/p/8092823.html
Copyright © 2020-2023  润新知