2012-11-21 3 views
0

this fiddle example 다른 범위에있는 ng-repeat에서 값을 설정하려고합니다. 이것은 내가 해결하려고하는 훨씬 더 큰 문제의 아주 기본적인 예입니다. 기본적으로 ng-repeat에 변수를 설정하여 각도가 템플릿을 적절히 업데이트하도록해야합니다. 문제는 템플릿이 하위 컨트롤러에 있다는 것입니다. 그래서 나는 $ 컨트롤러 injectable을 사용하여 변수에 접근한다. 그러나이 변수를 업데이트해도 템플릿이 업데이트되지 않습니다. 범위를 지정하더라도 $ apply(). 누구든지 아이디어가 있습니까? 이 작업을 수행하는 또 다른 방법은 확실하지 않습니다. ...앵글 js의 부모 범위에서 자식 범위의 템플릿을 업데이트

var myApp = angular.module('myApp', []); 

myApp.directive("custdirective", function() { 
    return { 
     restrict: 'A', 
     scope: 'false', 
     link: function(scope, element, attr) { 
      element.on("click", function() { 
      anotherscope.addList(); 
      }); 
     } 
    } 
}); 

function AnotherController($scope) { 
    $scope.listtwo = new Array(); 
    $scope.addList = function() { 
     $scope.listtwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
    } 
} 

function MyCtrl($scope, $controller, $rootScope) { 
    anotherscope = $rootScope.$new(); 
    $scope.anothercontroller = $controller(AnotherController, { 
     $scope: anotherscope 
    }); 
}​ 

올바르게 수행하려면 서비스를 생성해야합니다. 나는 올바른 방법의 업데이트 된 바이올린이 here 또는 수행했다 : 그 조금 남았습니다처럼 주위

var myApp = angular.module('myApp', []); 

myApp.factory("mySharedService", function($rootScope) { 
    var sharedService = {}; 
    sharedService.message = ''; 

    sharedService.prepForBroadcast = function() { 
     this.message = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
     this.broadcastItem(); 
    }; 
    sharedService.broadcastItem = function() { 
     $rootScope.$broadcast('handleBroadcast'); 
    }; 

    return sharedService; 

}); 

myApp.directive("custdirective", function() { 
    return { 
     restrict: 'A', 
     scope: 'false', 
     link: function(scope, element, attr) { 
      element.on("click", function() { 
       debugger; 
       scope.handleClick(); 
      }); 
     } 
    } 
}); 

function AnotherController($scope, sharedService) { 
    $scope.listtwo = new Array(); 
    $scope.addList = function() { 
     $scope.listtwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
    } 

    $scope.$on('handleBroadcast', function() { 
     $scope.listtwo = sharedService.message; 
    $scope.$apply(); 
    }); 
} 

function MyCtrl($scope, sharedService) { 
    $scope.handleClick = function() { 
     sharedService.prepForBroadcast(); 
    }; 
} 


MyCtrl.$inject = ['$scope', 'mySharedService'];   

AnotherController.$inject = ['$scope', 'mySharedService'];​ 

답변

3

합격 범위를 거의 귀하의 각도 응용 프로그램의 테스트 용이성을 깰 보장됩니다.

creating a service 컨트롤러와 지시문 사이의 변경 사항을 중개하는 것이 더 좋을 것이라고 생각합니다. 이 서비스에는 업데이트하고자하는 배열이나 지시문에서 호출하고자하는 함수가 포함됩니다.

저는 궁극적 인 목표가 무엇인지 이해하지 못하기 때문에 그러한 서비스의 예를 작성하는 것이 어렵습니다.

+0

나는 대답을 기다리는 동안 각도로 서비스를 들여다 보며이 녀석 (http://jsfiddle.net/ADukg/1412/)을 생각해 냈습니다. 내가해야 할 일을하는 것처럼 보입니다. 팁 고마워. – yaegerbomb