angularjs directive call function specified in attribute and pass an argument to it

后端 未结 7 796
难免孤独
难免孤独 2020-12-22 17:11

I want to create a directive that links to an attribute. The attribute specifies the function that should be called on the scope. But I also want to pass an argument to the

7条回答
  •  不知归路
    2020-12-22 17:53

    You can create a directive that executes a function call with params by using the attrName: "&" to reference the expression in the outer scope.

    We want to replace the ng-click directive with ng-click-x:

    
    

    If we had this scope:

    $scope.a = 2;
    $scope.b = 2;
    
    $scope.add = function (a, b) {
      $scope.result = parseFloat(a) + parseFloat(b);
    }
    

    We could write our directive like so:

    angular.module("ng-click-x", [])
    
    .directive('ngClickX', [function () {
    
      return {
    
        scope: {
    
          // Reference the outer scope
          fn: "&ngClickX",
    
        },
    
        restrict: "A",
    
        link: function(scope, elem) {
    
          function callFn () {
            scope.$apply(scope.fn());
          }
    
          elem[0].addEventListener('click', callFn);
        }
      };
    }]);
    

    Here is a live demo: http://plnkr.co/edit/4QOGLD?p=info

提交回复
热议问题