gpt4 book ai didi

javascript - 如何使子链接指令函数在父 Controller 之前运行?

转载 作者:行者123 更新时间:2023-11-30 16:39:24 24 4
gpt4 key购买 nike

指令代码

.directive('directive',function(){
return {
link:function(scope){
scope.a1='ok'
scope.b1='ok'
scope.c1='ok'
}
}
})

Controller 代码:

.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


我希望 a 没问题。但是当我声明它($scope.a==$scope.a1)时,指令链接函数还没有运行。我该怎么办?

最佳答案

您可以使用 $emit()$on()

  • $emit() 通过范围层次结构向上调度事件。
  • $on() 监听特定事件

因此,在您的情况下,您可以执行以下操作:

Controller

(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>

你可以看到 Working Plunker

关于javascript - 如何使子链接指令函数在父 Controller 之前运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32229647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com