我如何使一个指令像在angular中的其他内置指令一样运行一个函数?
例如:
<div ng-repeat="someId in myList" my-directive="runFunctionInScope(someId, divHtmlElement)" />
myApp.directive('myDirective', function ()
{
return function (scope, element, attrs)
{
//??
}
}
答案 0 :(得分:1)
您可以尝试以下代码段。另外,请检查this plunker以获得给定方案的工作示例。
模板:
<div ng-repeat="someId in myList" my-method='theMethodToBeCalled' my-id='someId.id' />
控制器:
app.controller('MainCtrl', function($scope) {
$scope.myList=[{
id: 1,
value: 'One'
}, {
id: 2,
value: 'Two'
}];
$scope.theMethodToBeCalled = function(id) {
alert(id);
};
});
指令:
app.directive("myMethod",function($parse) {
var directiveDefinitionObject = {
restrict: 'A',
scope: {
method:'&myMethod',
id: '=myId'
},
link: function(scope,element,attrs) {
var expressionHandler = scope.method();
expressionHandler(scope.id);
}
};
return directiveDefinitionObject;
});