![](/img/trans.png)
[英]Get number of child directives in parent directive before link function is executed
[英]How to make the child link directive function to run before parent controller?
指令代碼
.directive('directive',function(){
return {
link:function(scope){
scope.a1='ok'
scope.b1='ok'
scope.c1='ok'
}
}
})
控制器代碼:
.controller('controller',function($scope,$timeout){
$scope.a=$scope.a1
$timeout(function(){
$scope.b=$scope.b1
},100)
})
結果:
the scope.a1 ="" but needs to be 'ok'
the scope.b = "ok" but needs to be 'ok'
the scope.c1 = "ok" but needs to be 'ok'
演示: http : //plnkr.co/edit/80XojfqrrKNubi17TeHq?p=preview
我想, 一個是確定。 但是當我聲明它($ scope.a == $ scope.a1)時,指令鏈接功能尚未運行。 我該怎么辦?
使它類似於$scope.b=$scope.b1
,將$scope.a=$scope.a1
放入$timeout
函數中。
$timeout
將延遲執行直到下一個周期。 然后,在編譯子指令之后,完成分配。
如果您不想使用$timeout
,則需要應用一些異步機制來延遲分配(直到child指令完成編譯)。 例如$http.get(..).then()..
等
或者,將賦值語句放在子指令中。 無論如何,父母和孩子使用完全相同的$scope
對象。
第三,使用event
系統發布/訂閱事件和調用處理程序。
無論如何,您需要通過某種異步機制來延遲父級中的賦值語句。
您可以使用$ emit()和$ on() 。
因此,根據您的情況,您可以執行以下操作:
調節器
(function(){
function Controller($scope) {
//Listen for change event sent by the directive
$scope.$on('change', function(){
//Set our $scope value
$scope.a = $scope.a1;
$scope.b = $scope.b1;
})
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
指示
(function(){
function directive() {
return {
link:function(scope){
scope.a1='ok';
scope.b1='ok';
scope.c1='ok';
//Send change event
scope.$emit('change');
}
};
}
angular
.module('app')
.directive('directive', directive);
})();
HTML
<body ng-app='app' ng-controller="ctrl">
<div directive>
the scope.a1 ="{{a}}" but needs to be 'ok'
<br>
the scope.b = "{{b}}" but needs to be 'ok'
<br>
the scope.c1 = "{{c1}}" but needs to be 'ok'
</div>
</body>
您可以看到工作柱塞
通常這是不可能的(主要是如果您認為您的模板可能包含異步ng-include
include)。
因此,您需要一種回調機制,該機制將告訴控制器已加載/就緒的東西。 這可以通過多種機制來實現:
$watch
。 實際使用哪一個取決於用例。 至少給出一個例子,這里是回調:
angular.module('foo', []).
controller('FooController', function() {
this.init = function() {
// Do some stuff
};
}).
directive('foo', function() {
return {
link: function(scope, element, attrs) {
scope.$eval(attrs.foo); // Call controller
}
};
});
<div ng-controller="FooController as fooController">
<div foo="fooController.init()"></div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.