AngularJS:指令通过控制器与其他指令通信API

AngularJS: Directive communicating with other other directives via controller API

子指令与父指令通信

下面的代码完美运行,除非我取消注释父指令 (parentD) 中的模板行

.directive('parentD', ['$window', function($window) {
  return {
    restrict: 'E',
    scope: {},
    controller: function($scope) {
      this.testvar = 'Hello';
      this.doSomething = function() {
        $window.alert("This is an alert from the parent");
        return this.testvar;
      }
    },
    //template: '<h1>Parent Template</h1>'
  }
}])
.directive('childD', ['$window', function($window) {
  return {
    restrict: 'E',
    require: '^parentD',
    scope: {},
    template: '<h2>Child Template</h2>',
    link: function(scope, element, attribute, controller) {
      $window.alert('The parent passes this message ' + controller.doSomething());
    }
  }

当这一行取消注释时,似乎没有执行子指令。

http://plnkr.co/edit/h3bMe5mJ0QnbRHIla8l9

感谢您的帮助,我确定我在某个地方犯了错误,我只是需要多一双眼睛。

(function(angular) {
  'use strict';
  angular.module('directiveExample', [])
    .directive('parentD', ['$window', function($window) {
      return {
        restrict: 'E',
        scope: {},
        replace:true,
        transclude: true,
        controller: function($scope) {
          this.testvar = 'Hello';
          this.doSomething = function() {
            $window.alert("This is an alert from the parent");
            return this.testvar;
          }
        },
        template: '<div><h1>Parent Template</h1><div ng-transclude></div></div>'
      }
    }])
    .directive('childD', ['$window', function($window) {
      return {
        restrict: 'E',
        require: '^parentD',
        replace:true,
        scope: {},
        template: '<div><h2>Child Template</h2></div>',
        link: function(scope, element, attribute, controller) {

          $window.alert('The parent passes this message ' + controller.doSomething());
        }
      }
    }])
})(window.angular);

我想你会明白我所做的。 但请随时提出任何问题。 现在检查您的两个模板是否正常工作。 在这里,我在父模板中使用 ng-transclude 来显示父模板内容以及子模板(及其内容),因为我们有父子场景。

你可以检查这个工作link, http://plnkr.co/edit/pIkN5Uc3JYQpsbKOMcY1?p=preview