AngularJS指令在数据之前加载

Dav*_*ave 7 angularjs angularjs-directive

假设我正在使用$ http将变量加载到$ scope中:

$http.get('/teachers/4').success(function(data){
  $scope.teacher = data;
});
Run Code Online (Sandbox Code Playgroud)

我的模板使用这些数据:

Teacher: {{teacher.name}}
<students-view students="teacher.students"></students-view>
Run Code Online (Sandbox Code Playgroud)

该指令可以加载BEFORE老师完成加载,但我的指令的代码取决于正在加载的teacher.students数组:

app.directive('studentsView', function(){
  return {
    scope: { students: '=' },
    controller: function($scope){
      _.each($scope.students, function(s){
        // this is not called if teacher loads after this directive
      });
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

我如何得到我想要的行为?我不想停止使用$ http,如果可能的话,我不想为范围分配承诺.

use*_*490 20

使用手表等待students可用.一旦可用,您可以调用依赖它的代码,然后移除手表.如果希望每次students更改时都执行代码,则可以跳过删除监视.

app.directive('studentsView', function(){
  return {
    scope: { students: '=' },
    link: function($scope){
      var unwatch = $scope.$watch('students', function(newVal, oldVal){
        // or $watchCollection if students is an array
        if (newVal) {
          init();
          // remove the watcher
          unwatch();
        }
      });

      function init(){
        _.each($scope.students, function(s){
          // do stuff
        });
      }
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

  • @Dave在DOM编译过程中,指令控制器在链接函数之前被实例化,因此链接函数基本上可以看作是在结束/稳定状态下运行.当您希望将API公开给其他指令时,Angular文档建议使用[_controller.否则请使用链接](https://docs.angularjs.org/guide/directive#summary)_.有些人则反驳说:[定义指令时'控制器','链接'和'编译'函数之间的区别](http://stackoverflow.com/a/12570008/2943490).这取决于上述排序是否与您的用例有关. (2认同)