针对独立 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 参数。
浙公网安备 33010602011771号