如何使自定义指令 运行 在 angularjs 1.x 中起作用?

How to make custom directive run function in angularjs 1.x?

如何使指令 运行 成为类似于 angular 中其他内置指令的函数?

例如:

<div ng-repeat="someId in myList" my-directive="runFunctionInScope(someId, divHtmlElement)" />


myApp.directive('myDirective', function ()
{
    return function (scope, element, attrs)
    {
        //??
    }
}

您可以尝试类似下面的代码片段。另请检查 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;
});