在AngularJs中,父指令如何调用在其子指令中定义的函数

In AngularJs , how does the parent directive call the function which is defined in its child directive?

本文关键字:指令 定义 函数 调用 AngularJs 何调用      更新时间:2023-09-26

我想调用子指令中的函数,而不是使用$scope.$broadcast通知子指令发生了什么事情。外部指令将在不同的时间调用不同子指令中的不同函数。

您可以在指令中使用控制器
例如:在子指令的链接函数中,您可以将所需内容保存在父控制器中,然后在需要时调用。

样品

angular.module('app', [])
  .directive('parent', function() {
    return {
      controller: function() {
        var parent = this;
        parent.childs = [];
        parent.click = function() {
          parent.childs.forEach(function(child) {
            child.addOne();
          });
        }
      },
      controllerAs: 'vm'
    }
  })
  .directive('child', function() {
    return {
      require: ['child', '^parent'],
      template: '<div>Child value: {{vm.val}} <input type="button" ng-click="vm.addOne()" value="add one" /></div>',
      controller: function() {
        var child = this;
        child.addOne = function() {
          child.val += 1;
        }
      },
      controllerAs: 'vm',
      scope: true,
      link: function(scope, elem, attrs, ctrls) {
        var childCtrl = ctrls[0],
          parentCtrl = ctrls[1];
        parentCtrl.childs.push(childCtrl);
        childCtrl.val = +attrs.child;
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<div ng-app="app">
  <div parent>
    <input type="button" ng-click="vm.click()" value="add one to all" />
    <div child="1"></div>
    <div child="2"></div>
    <div child="3"></div>
  </div>
</div>

我们需要在父指令作用域中创建一个空对象,并将其作为参数传递给子指令。

在子指令中接收它时,我们可以向它注入方法

app.directive('childDirective', function () {
    return {
        restrict: 'E',
        scope: {
        objectToInject: '=',
        },
        templateUrl: 'templates/myTemplate.html',
        link: function ($scope, element, attrs) {
            var killwatch = $scope.$watch('objectToInject', function (value) {
                if(value){
                $scope.Obj = value;
                    /*Injecting the Method*/
                    $scope.Obj.invoke = function(){
                        //Do something
                    }
                    killwatch();
                }    
            });
        }
    };
});

并使用该对象从父对象调用子指令函数。