【问题标题】:AngularJS directive loading before dataAngularJS指令在数据之前加载
【发布时间】:2015-02-17 21:22:33
【问题描述】:

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

$http.get('/teachers/4').success(function(data){
  $scope.teacher = data;
});

我的模板使用了这些数据:

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

该指令可以在教师完成加载之前加载,但我的指令的代码取决于正在加载的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,并且如果可能的话,我希望不必为范围分配承诺。

【问题讨论】:

  • 循环中发生了什么?如果有帮助,可以将该循环放入控制器中的成功回调中,或者将整个请求移至服务

标签: angularjs angularjs-directive


【解决方案1】:

使用手表等待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
        });
      }
    }
  };
});

【讨论】:

【解决方案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
        });     
      };
    }
  };
});

更多关于$watchhttps://docs.angularjs.org/api/ng/type/$rootScope.Scope

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多