2014-12-02 100 views
2

我有一个Angular JS的问题。我有两个指令。从Angular JS 1.3传递父元素到子元素的属性

angular.module('myModule', []) 
    .directive('myFirstDirective', function(){ 
     return { 
      link: function (scope, elem, attr) { 
       var myAttributeToPass = attr.myFirstDirective; 
       scope.myAttr = myAttributeToPass; 
      }, 
      controller: 'MyFirstController' 
     } 
    }) 
    .controller('MyFirstController', function($scope){ 
     this.returnTheParameter = function(){ 
      return $scope.myAttr; 
     } 
    }) 
    .directive('mySecondDirective', function(){ 
     return { 
      require : ['ngModel', '^myFirstDirective'], 
      link : function($scope, element, attrs, ctrls) { 
       var ngModel = ctrls[0]; 
       var myFirstCtrl = ctrls[1]; 

       var theParamOfFirst = myFirstCtrl.returnTheParameter(); 
      } 
     } 
    }); 

我初始化我的第一个值与一个字符串:

<div my-first-directive="foobar"> (... => my second directive is inside) </div> 

我的问题是在生命周期中,返回的值始终是不确定的,因为控制器的连接之前调用。当我做一个孤立的范围的,具有:

scope: { 
    "myProp": "@myFirstDirective" 
} 

这是工作,但我不想范围隔离...

任何想法?

非常感谢!

回答

1

问题在于操作发生的顺序。

听起来你需要按照特定的顺序编译东西。在这种情况下,我想引用你到这个职位:How to execute parent directive before child directive?所以我不借借他人的全部解释。

最终你会想要做的线沿线的东西:你的第一个指令,并在第二个指令

return { 
     compile: function(){ 
      return{ 
      pre:function (scope, elem, attr) { 
       var myAttributeToPass = attr.myFirstDirective; 
       scope.myAttr = myAttributeToPass; 
      }, 
      post: angular.noop 
      }; 
     }, 
     controller: 'MyFirstController' 
    }; 

return { 
     require : ['^myFirstDirective'], 
     compile: function(tElement, tAttrs, transclude){ 
      return{ 
      pre: angular.noop, 
      post: function($scope, element, attrs, ctrls) { 
       var ngModel = attrs.ngModel; 
       var theParamOfFirst = ctrls[0].returnTheParameter(); 
      } 
      }; 
     } 
    }; 

以上angular.noop只是一个空方法返回什么。 对于一个工作的例子,随意浏览我扔在一起的朋克(http://plnkr.co/edit/pe07vQ1BtTc043gFZslD?p=preview)。

+1

非常感谢,它完美的作品! :) – Ndrou 2014-12-03 08:37:18

相关问题