2014-12-18 2 views
7

전에 지시로드의 내가 $의 HTTP와 $ 범위에 변수를로드하고있어 가정 해 봅시다AngularJS와 데이터

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

가 어떻게 할 :로드,하지만 내 지시어는로드되는 teacher.students 배열에 따라 코드가 내가 원하는 행동을 해? 나는 $ http를 사용하는 것을 멈추고 싶지 않으며, 가능한 한 범위에 약속을 할 필요가 없다.

+0

루프에서 무슨 일이 일어나고 있습니까? 컨트롤러에서 성공 콜백 내에 루프를 넣을 수 있습니다. 전체 요청을 돕거나 서비스로 이동하는 경우 – charlietfl

답변

20

시계를 사용하여 students을 사용할 수있을 때까지 기다리십시오. 사용할 수있게되면 코드에 의존하는 코드를 호출 한 다음 시계를 삭제합니다. students 변경 될 때마다 코드를 실행하려면 시계 제거를 건너 뛸 수 있습니다.

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에 :

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

+2

@Dave DOM 컴파일 프로세스에서 지시문 컨트롤러는 링크 함수보다 먼저 인스턴스화되므로 링크 함수는 본질적으로 최종/안정 상태에서 작동하는 것으로 볼 수 있습니다. Angular 문서는 API를 다른 지시어에 표시하려는 경우 [_controller]를 사용하는 것이 좋습니다. 그렇지 않으면 링크를 사용하십시오] (https://docs.angularjs.org/guide/directive#summary) _. 달리 말하자면 : [지시어를 정의 할 때 '컨트롤러', '링크'및 '컴파일'기능의 차이점] (http://stackoverflow.com/a/12570008/2943490). 앞서 말한 순서가 당신의 유스 케이스에 중요한지 여부에 달려 있습니다. – user2943490