AngularJS指令在数据之前加载

时间:2014-12-18 23:35:10

标签: angularjs angularjs-directive

假设我正在使用$ http:

将变量加载到$ scope中
$http.get('/teachers/4').success(function(data){
  $scope.teacher = data;
});

我的模板使用此数据:

Teacher: {{teacher.name}}
<students-view students="teacher.students"></students-view>

这个指令可以加载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
      });
    }
  };
});

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

2 个答案:

答案 0 :(得分: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
        });
      }
    }
  };
});

答案 1 :(得分:2)

您可能需要在students上进行某种观察,以了解何时更新,然后在触发观看时运行您的_.each

app.directive('studentsView', function(){
  return {
    scope: { students: '=' },
    controller: function($scope){
      scope.$watch('students', function(newValue, oldValue) {
        _.each($scope.students, function(s){
          // this is not called if teacher loads after this directive
        });     
      };
    }
  };
});

有关$watch的更多信息:https://docs.angularjs.org/api/ng/type/$rootScope.Scope

相关问题