2014-06-22 2 views
1

이 예가 될 것입니다 설명하는 가장 좋은 방법 :반복에서 단일 자식 컨트롤러에 액세스 하시겠습니까?

<table ng-controller="groupOfPeopleController"> 
    <tr ng-repeat "person in peoples"> 
     <td>{{person.name}}</td> 
     <td><button ng-click="load_data(person.id)">Load Data</button> 
     <td><div class="personData" ng-controller="personDataController"></div></td> 
    </tr> 
</table> 

내가 무엇을 찾고 있어요 것은 그 자체가 데이터 div.personData를 채우는 것입니다. 내가 좋아하는 것

// groupOfPeopleController 
$scope.load_data = function(id){ 
    $rootScope.$broadcast('load_data'id); 
} 

는 자식 요소 컨트롤러 personData에 특이 적으로 전달하는 데 : 그래서 groupOfPeopleController에서 함수가 load_data (ID)라고합니다.

// personDataController 
$scope.$on('load_data',function(e,id){ 
    // hopefully affect only the div inside the current loop... 
}); 

문제는 personData의 모든 루프에 첨부된다는 점입니다. 한 사람을 클릭하면 모든 행에 영향을 미치며 모두 동일한 컨트롤러에 연결되어 있습니다.

어떻게 personData 인스턴스를 별도로 만들까요? 이 문제를 해결하기 위해 방송이 잘못 되었습니까?

답변

1

$ rootScope에서 브로드 캐스팅하지 마십시오. 모든 자식 범위 (및 해당 자식을 재귀 적으로)로 아래쪽으로 이벤트 이름을 전달합니다.

당신이 할 수있는 일은 모든 범위가 아닌 현재 범위의 방송입니다. 이 plunker을 참조하십시오.

주요 트릭은 하위 범위 ng-repeat가 필요하므로 현재 범위를 가져 오는 함수에 키워드 "this"를 전달한 다음 거기에서 이벤트를 브로드 캐스트합니다.

요소 :

<button ng-click="load_data(this, person.id)">Load Data</button> 

groupOfPeopleController :

$scope.load_data = function(childScope, id){ 
    childScope.$broadcast('load_data', id); 
} 

는 그러나, 나는이 방법에 대해 권장합니다. 왜 모든 브로드 캐스트/$ on을 사용합니까? personDataController를 tr의 전체 내용으로 이동하고 this plunker과 같이 ng-click에서 loadData 함수를 직접 호출 할 수 있습니다. 그것은 당신에게 두통과 버그를 저장합니다.

+0

우수. 고맙습니다. –

1

브로드 캐스트를 사용하지 마십시오. 예, 이벤트는 좋지만이 경우에는 아닙니다. 루프의 모든 항목이 인스턴스가 아닌 동일한 컨트롤러에 대한 참조를 받기 때문에 루프의 항목이 업데이트되고 있습니다.

지시어를 사용하는 올바른 방법입니다.

는 당신의 템플릿을 변경

:

<tr ng-repeat="person in peoples" data-person="person"></tr> 

이 같은 지침 뭔가 사용

app.directive('person', function(){ 
    var templateStr = '<td>{{person.name}}</td>' + 
     '<td><button ng-click="load_data(person.id)">Load Data</button>' + 
     '<td><div class="personData">{{person.anyDataYouWantToDisplay}}</div></td>'; 
    var linkFn = function(scope){ 
     scope.load_data = function(id){ 
      // load person data and do something about it 
     }; 
     // do other magic here as it is the controller for your individual person 
    }; 
    return { 
     restrict: 'A', 
     scope: { 
      person: '=' 
     } 
     link: linkFn, 
     template: templateStr 
    }; 
}); 

희망하는 데 도움이됩니다.

+0

이것은 엄청난 도움이됩니다. 귀하의 의견을 보내 주셔서 감사합니다. 내가 이미 한 일에 조금 더 가까웠 기 때문에 나는 다른 대답을 선택했다. 그러나 큰 대답은 없다. –

관련 문제