2014-12-18 45 views
7

之前指令裝載比方說,我加載一個變量爲$範圍與$ HTTP:AngularJS數據

$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,如果可能的話,我不希望爲範圍分配一個承諾。

+0

循環中發生了什麼?可以將該循環放入控制器中的成功回調中,如果這有助於或將整個請求移動到服務中 – charlietfl 2014-12-19 00:00:34

回答

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 
     }); 
     } 
    } 
    }; 
}); 
+0

將此代碼放入控制器函數並將其放入鏈接函數中有什麼區別? – Dave 2014-12-19 10:52:45

+2

@Dave在DOM編譯過程中,指令控制器在鏈接函數之前得到實例化,所以鏈接函數基本上可以看作是在最終/穩定狀態下進行操作。 Angular文檔建議在您想將API暴露給其他指令時使用[_controller]。否則使用鏈接](https://docs.angularjs.org/guide/directive#summary)_。有些人反對:[定義指令時'控制器','鏈接'和'編譯'函數之間的區別](http://stackoverflow.com/a/12570008/2943490)。這取決於上述排序是否對您的用例有影響。 – user2943490 2014-12-19 11:25:28

1

你可能需要做一些手錶上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