如何从父指令/控制器访问指令范围

How do I access a directive scope from a parent directive/controller?

本文关键字:指令 控制器 访问 范围      更新时间:2023-09-26

我有一个模板是这样的:

<parent-directive>
    <child-directive binding="varFromParent"></child-directive>
    <button ng-click="parentDirective.save()"></button>
</parent-directive>

parentDirective控制器中执行函数时,是否可以访问和操作childDirective的作用域变量,例如,如果我将它们设置为这样

angular.module('app').directive('parentDirective', function() {
  return {
    restrict: 'E',
    templateUrl: '...',
    controllerAs: 'parentDirective',
    controller: function($rootScope, $scope) {
      //...
      this.save = () => {
        //Need to manipulate childDirective so that its
        //scope.defaultValue == 'NEW DEFAULT' 
      }
    }
  }
});

angular.module('app').directive('childDirective', function() {
  return {
    restrict: 'E',
    templateUrl: '...',
    scope: {
        binding: '='
    }, 
    controllerAs: 'childDirective',
    link: function(scope, elm, attrs) {
      scope.defaultValue = 'DEFAULT';
    }
  }
});

我将如何做到这一点?有没有办法在不设置双向绑定的情况下做到这一点?如果可能的话,我想避免<child-directive>元素上的属性混乱。

有很多方法可以在您的孩子和家长指令之间建立通信:

  1. 双向绑定(就像你说的)

  2. 在父母中登记您的孩子

    可以使用指令 require 属性和链接函数的最后一个参数controllers在其父级中注册子项。

  3. 事件,请参阅$scope.on/broadcast

  4. Angular 服务(因为它们是"单例",因此很容易使用它在指令之间共享数据)

等。

示例 2:

angular.module('Example', [])
.directive('parent', [function () {
    return {
        controller: function (){
            // registerChildren etc
        }
        // ...
    };
}])
.directive('children', [function () {
    return {
        require: ['^^parent', 'children'],
        controller: function (){
            // ...
        }
        link: function ($scope, element, attributs, controllers) {
            ParentController = controllers[0];
            OwnController = controllers[1];
            ParentController.registerChildren(OwnController);
            // ...
        }
        // ...
    };
}])

在这种情况下,您可能不需要隔离子指令范围。定义一个需要在父级的作用域上更改的变量,然后子级的指令作用域将继承此值,以便您可以在子级指令中更改它的值,并且可以从父级访问它。

angular.module('app').directive('parentDirective', function() {
  return {
    restrict: 'E',
    controllerAs: 'parentCtrl',
    controller: function($scope) {
      $scope.value = 'Value from parent';
      this.value = $scope.value
      this.save = function() {
        this.value = $scope.value;
      }
    }
  }
});
angular.module('app').directive('childDirective', function() {
  return {
    restrict: 'E',
    controllerAs: 'childCtrl',
    controller: function($scope) {
        $scope.value = 'Value from child';
      this.setValue = function() {
        $scope.value = 'New value from child';
      }
    }
  }
});

这是小提琴http://jsfiddle.net/dmitriy_nevzorov/fy31qobe/3/