다음은 두 컨트롤러간에 값을 전달/동기화하려는 샘플 코드입니다. 동일한보기의 경우 텍스트 상자와 텍스트 상자의 값을 표시하는 두 개의 자리 표시자가 있습니다.각도 컨트롤러 간 데이터 전달
나는 어떻게 든 동작을 달성했지만 여전히 코드가 한 곳에서 작동하지 않고 다른 곳에서 잘 작동 하는지를 파악할 수 없었습니다. 나는 두 가지 방법, 한 가지는 작동하고 (두 번째 방법), 하나는 그렇지 않다는 것을 언급했다.
나는 다음과 같은 사용했다 :
- 1 서비스
- 2 컨트롤러
- 1보기
서비스
mcApp.factory('mcService', function($rootScope){
var service = {};
//variable 1
service.message = 'Default';
//function 1
service.getMessage = function(){
return this.message;
}
//function 2
service.setMessage = function(msg){
this.message = msg;
}
return service;
});
컨트롤러 - 첫 번째 방법 -
mcApp.controller('mcController1', function ($scope, mcService) {
$scope.message = mcService.getMessage();
$scope.setmsg = function(msg){
mcService.setMessage(msg);
}
});
mcApp.controller('mcController2', function($scope, mcService){
$scope.message = mcService.getMessage();
});
보기 작동하지 않음 - 첫 번째 방법 - 서비스를 호출하여 위의 코드 내가 범위 변수 "메시지"의 값을 업데이트하고에서
<div ng-app="mcApp">
<div ng-controller="mcController1">
<input type="text" ng-model="message" ng-change="setmsg(message)">
<p ng-bind="message"></p>
</div>
<div ng-controller="mcController2">
<p ng-bind="message"></p>
</div>
</div>
작동하지 않음 "mcController2"의 "getMessage()"메소드. 그러나 뷰에서 업데이트되지 않습니다.
다음은 "mcController2"에서 "getMessage()"서비스 메서드를 직접 사용하는 대신 범위 변수에 서비스를 할당 한 코드입니다. 에서 컨트롤러 사용하여 서비스 $rootScope.$broadcast
및 $scope.$on
:
컨트롤러 - 두 번째 방법 - 작업
mcApp.controller('mcController1', function ($scope, mcService) {
$scope.message = mcService.getMessage();
$scope.setmsg = function (msg) {
mcService.setMessage(msg);
}
});
mcApp.controller('mcController2', function ($scope, mcService) {
$scope.service = mcService;
});
보기 - - 두 번째 방법으로 작업
<div ng-app="mcApp">
<div ng-controller="mcController1">
<input type="text" ng-model="message" ng-change="setmsg(message)">
<p ng-bind="message"></p>
</div>
<div ng-controller="mcController2">
<p ng-bind="service.message"></p>
</div>
</div>
참고하시기 바랍니다 첫 번째 방법은 또한 th를 얻습니다. 전자 일. 하지만 이유를 알아낼 수 없습니다 Fisrt way가 작동하지 않습니다.
두 번째 방법이 효과가있을 지 확실하지 않습니다. 그거 확실하니? 당신은 plunkr에서 그것을 설명 할 수 있습니까? – SLearner