加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS指令在数据之前加载

发布时间:2020-12-17 07:20:10 所属栏目:安全 来源:网络整理
导读:假设我正在使用$http将变量加载到$scope中: $http.get('/teachers/4').success(function(data){ $scope.teacher = data;}); 我的模板使用这些数据: Teacher: {{teacher.name}}students-view students="teacher.students"/students-view 该指令可以加载BEFO
假设我正在使用$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,如果可能的话,我不想为范围分配承诺.

使用手表等待学生可用.一旦可用,您可以调用依赖它的代码,然后移除手表.如果您希望每次学生更改时执行代码,您都可以跳过删除手表.
app.directive('studentsView',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
        });
      }
    }
  };
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读