2015-09-08 37 views
0

儿童指令与母指令

下面下面的代码完美地工作,进行通信时除外我去掉在父指令模板线(parentD)AngularJS:经由控制器API以外的其它指令指令连通

.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

感谢您的帮助,我敢肯定,我犯了一个错误的地方,我只需要一组额外的它的眼睛。

+0

需要使用“this”关键字如在我的答案。 – micronyks

+0

感谢您的回复,您的代码看起来与我上面发布的代码完全相同,您能告诉我区别在哪里吗?您是否取消了父级模板行的注释?我认为可能对我最近的抢注没有保存造成混乱,我已经更新了它以反映我原始帖子中的代码。 –

+0

http://plnkr.co/edit/pIkN5Uc3JYQpsbKOMcY1?p=preview请检查这个链接和我的整个更新的答案。你将拥有你正在寻找的工作模板和所有消息。 – micronyks

回答

0
(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来显示父模板内容以及子模板(及其内容),因为我们有父子模式。

您可以检查这方面的工作环节, http://plnkr.co/edit/pIkN5Uc3JYQpsbKOMcY1?p=preview

+0

**完美**,我尝试过自我传递,但我没有在父模板中包含ng-transclude,这在现在很合理。谢谢你的帮助! –