AngularJS指令在数据之前加载

前端之家收集整理的这篇文章主要介绍了AngularJS指令在数据之前加载前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我正在使用$http将变量加载到$scope中:
  1. $http.get('/teachers/4').success(function(data){
  2. $scope.teacher = data;
  3. });

我的模板使用这些数据:

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

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

  1. app.directive('studentsView',function(){
  2. return {
  3. scope: { students: '=' },controller: function($scope){
  4. _.each($scope.students,function(s){
  5. // this is not called if teacher loads after this directive
  6. });
  7. }
  8. };
  9. });

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

使用手表等待学生可用.一旦可用,您可以调用依赖它的代码,然后移除手表.如果您希望每次学生更改时执行代码,您都可以跳过删除手表.
  1. app.directive('studentsView',link: function($scope){
  2. var unwatch = $scope.$watch('students',function(newVal,oldVal){
  3. // or $watchCollection if students is an array
  4. if (newVal) {
  5. init();
  6. // remove the watcher
  7. unwatch();
  8. }
  9. });
  10.  
  11. function init(){
  12. _.each($scope.students,function(s){
  13. // do stuff
  14. });
  15. }
  16. }
  17. };
  18. });

猜你在找的Angularjs相关文章