2014-07-22 82 views
4

我在同一頁面上有兩個指令,但在另一個元素上。 類似的東西:Angularjs:指令加載順序

<div directive-one> 
    <div directive-two></div> 
</div> 

在directiveOne,我創建一些變量(比方說,$scope.pageConfig.variable)。 我想指令兩個使用這個變量。

問題 - directiveOne不總是在directiveTwo之前加載。

問題是 - 有沒有辦法確保directiveOne在directiveTwo之前加載,以便該變量可用於directiveTwo?

謝謝:)

更新: 我已經找到了答案應該是在directiveOne使用控制器這樣的:

return { 
controller: function($scope){ $scope.variable = variable; }, 
link : ... 
} 

的問題是,我得到一個錯誤[$注入器:unpr]以這種方式使用時。這應該解決我的問題嗎?任何想法爲什麼這會給我造成一個錯誤?

+2

您可以給予指令1更高的優先級。請參閱https://docs.angularjs.org/api/ng/service/$compile - 優先 – hutingung

+0

請顯示您的指令代碼。你在哪裏把你的邏輯放在兩個指令中,postLink? – runTarm

+0

我把邏輯放在鏈接函數中。我試圖使用控制器,這應該工作,但我得到一個錯誤。現在我看到每次將控制器放入我的任何指令時都會出現錯誤。不管控制器中有什麼。奇怪... – yccteam

回答

3

我已經找到了答案。 一個解決方案可以是miron的解決方案。問題是,它爲正在等待孩子的指令(在問候DOM樹)母公司指令 -

你可以要求它父DOM元素上,或同一DOM元素

對我而言,另一種解決方案是使用指令的控制器。 This blog post解釋得非常好。簡而言之,控制器是按照dom樹的讀取順序激活的,而鏈接正在被讀取。

我的問題是,您必須接受控制器實際接受範圍的$ scope(如controller:function($ scope)而不是controller:function(scope))。不直觀,但這就是它的原理:)

-2

如果變量會更新,您可以隨時在變量上設置一個監視。

這裏有一個簡單的例子,

App.directive('myDirective', function() { 
    return { 
     restrict: 'AE', 
     replace: 'true', 
     link: function ($scope, element, attrs) 
     { 
      $scope.test = "testme" 
     } 
    }; 
}); 


App.directive('mySecondDirective', function() { 
    return { 
     restrict: 'AE', 
     replace: 'true', 
     link: function ($scope, element, attrs) 
     { 
      $scope.$watch('test', function() { 
         alert('hey, myVar has changed!'); 
     }); 
     } 
    }; 
}); 

作爲替代方案,你可以在第二個指令設置超時,

$scope.test = "Waiting to update"; 


setTimeout(function() { 
    $scope.$apply(function() { 
      console.log($scope.test); 
    }); 
}, 2000); 

希望這將幫助你!

+4

這不太好。 考慮dom元素與指令一起創建的情況(如kendoui小部件),並且此指令負責創建選項... – yccteam

+0

在最初的問題中沒有說明該情況 – Adam

6

如何要求directiveA在directiveB:

var myApp = angular.module('myapp', []) 
.run(function(){ 

}); 

myApp.directive('fooDirective', function() { 
    return { 
     restrict: 'A', 
     controller: function(){ 
     this.pageConfig = { 
      someVaraible: 'value from foo' 
     }; 
     } 
    } 
    }); 

    myApp.directive('barDirective', function() { 
    return { 
     restrict: 'A', 
     require: '^fooDirective', 
     link: function(scope, element, attr, fooDirectiveController){ 
     console.log(fooDirectiveController.pageConfig); 
     } 
    } 
    }); 

這裏有一個關於延伸指令一個Plunkinformation,這裏some more info

4

如果你想在孩子之前在父指令中運行一些代碼,你可以把你的代碼放在preLink函數中。preLink功能可以像這樣指定:

return { 
    link: { 
    pre: function preLink(scope, element, attrs) { 
     // put your code here 
     // code in here of parent will be executed before child's (top down). 
    }, 
    post: function postLink(scope, element, attrs) { 
     // code in here of parent will be executed after child's (bottom up). 
    } 
    } 
};