codeing or artist ?
记得大学第一节编程课,教授说,"如果一件事儿有对错,那么是科学。如果有美丑好坏,那么是艺术。" 一个能顺利运行还能让人阅读时体验思维美妙的代码,就是艺术和科学的结合。能运行的程序并不是好程序,能当作文章来读的才是。在我看来代码是一种特殊的文体,程序猿其实会写诗。

针对独立 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 参数。

posted on 2017-12-23 10:37  codeing-or-artist-??  阅读(163)  评论(0编辑  收藏  举报