如何在angularjs 1.x中使自定义指令运行功能?

时间:2018-08-28 12:05:55

标签: angularjs angularjs-directive

我如何使一个指令像在angular中的其他内置指令一样运行一个函数?

例如:

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


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

1 个答案:

答案 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;
});