如何使子链接指令函数在父控制器之前运行

How to make the child link directive function to run before parent controller?

本文关键字:控制器 运行 函数 何使 链接 指令      更新时间:2023-09-26

指令的代码

.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


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

您可以使用释放美元()美元在()

  • $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);
})();

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

你可以看到工作活塞

$scope.b=$scope.b1相似,将$scope.a=$scope.a1放在$timeout函数内。

$timeout将延迟执行到下一个周期。子指令编译完成后,赋值就完成了。


更新1

如果你不想使用$timeout,你需要应用一些异步机制来延迟赋值(直到子指令完成编译)。如:$http.get(..).then()..

或者,将赋值语句放在子指令中。无论如何,父节点和子节点使用完全相同的$scope对象。

第三,使用event系统发布/订阅事件和调用处理程序。

无论如何,您需要通过某种异步机制延迟父类中的赋值语句。

这通常是不可能的(主要是如果您认为您的模板可能包含异步ng-include include)。

你需要的是某种回调机制它会告诉控制器某事被加载/准备好了。这可以通过多种机制实现:

  1. 添加$watch在你的控制器的一些属性设置指令。
  2. 从指令中调用控制器回调方法。
  3. 从你的指令中发出一些事件,并在控制器中监听这个事件。

使用哪一个取决于用例。至少给出一个例子,下面是回调:

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>