2014-12-02 136 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

相關問題