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

时间:2016-04-15 07:58:30

标签: javascript angularjs

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

2 个答案:

答案 0 :(得分:1)

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

样品

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>

答案 1 :(得分:0)

我们需要在父指令范围内创建一个空对象,并将其作为参数传递给child指令。

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

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();
                }    
            });
        }
    };
});

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

相关问题