AngularJS指令使用参数运行回调 [英] AngularJS Directive Run Callback With Params
问题描述
我有一个非常简单的指令,我希望能够使用指令和作用域提供的参数运行回调。例如:
I've got a pretty simple directive that I'd like to be able to run a callback with parameters supplied by the directive and the scope. For example:
<div ng-repeat="user in users">
<div sample="..." callback="welcome(user, $message)">
</div>
</div>
我在使用 $ parse 来处理这个问题。我的示例指令如下:
I'm having trouble using $parse to handle this. My sample directive is as follows:
app.directive('sample', ['$parse', function ($parse) {
return {
restrict: 'A',
scope: {},
link: function (scope, element, attrs) {
// ...
function greet () {
var callback = $parse(attrs.callback);
callback(scope, { $message: 'Howdy' });
}
},
},
}]);
但是,尽管从$ parse获取函数 - 执行函数永远不会产生我的欢迎函数(已定义)在一个控制器中被调用(注意:在Angular 1.5.x上)。我假设范围是错误的(它使用隔离的范围而不是父范围) - 但我确实需要一个隔离的范围(例如简化)。我做错了什么?
However, despite getting a function from $parse - executing the function never results in my welcome function (defined in a controller) being called (note: on Angular 1.5.x). I'm assuming scope is wrong somehow (that it is using the isolated scope instead of the parent scope) - but I do need an isolated scope (simplified for example). What am I doing wrong?
推荐答案
你能否使用范围。$ parent
作为 $ parse
调用的参数?您可能还希望用 $ scope包装。$ apply(function(){...});
。
Can you use scope.$parent
as a parameter to your $parse
call? You may also wish to wrap with a $scope.$apply(function () { ... });
.
这篇关于AngularJS指令使用参数运行回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!