AngularJS 给 directive scope 绑定的 function 传参

如果我们想要给directive的scope中绑定的方法传递参数,需要传递对象,而不是直接传值。

举个栗子,这里的clickOutside是从用的地方传入的一个方法,debug时我们会发现绑进来的clickOutside并不是我们传的clickOutSideAction

1
2
3
4
5
6
7
8
9
10
11
12
13
app.directive('clickOutSide', ['$document', function($document) {
return {
restrict: 'A',
scope: {
clickOutside: '&'
},
link: function (scope, el) {
$document.on('click', function (e) {
scope.clickOutside();
});
}
}
}]);
1
<div data-click-out-side click-Outside="$ctrl.clickOutSideAction()"></div>

如果需要在这里给clickOutSideAction传参数,应该这样改:

1
2
3
4
5
6
7
8
9
10
app.directive('clickOutSide', ['$document', function($document) {
return {
...
link: function (scope, el) {
...
scope.clickOutside({event: e});
...
}
}
}]);
1
<div data-click-out-side click-Outside="$ctrl.clickOutSideAction(event)"></div>

好处是在实际使用directive的地方,不需要考虑参数列表顺序,只需要保证参数名称正确。

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×