2014-12-17 3 views
1

이제 컨트롤러와 컨트롤러간에 데이터를 공유하려고합니다. 내가 원하는 것은 controlA에서 입력 값을 업데이트 할 때마다 controlB의 값이 업데이트 될 때입니다. 내 문제가 어디 있는지 지적 해 주시겠습니까?angularjs에서 서비스를 사용하는 컨트롤러간에 데이터를 공유하고 업데이트하는 방법

var app = angular.module('app', []); 
app.factory('share', function() { 
    return { 
     user: {} 
    }; 
}) 
.controller('MainCtrl', function($scope, share) { 
    $scope.user = { 
     name: 'lin' 
    }; 
    share.user.name = $scope.user.name; 
    console.log(share.user.name); 
}) 
.controller('linctr', function($scope, share) { 
    $scope.super = { 
     name: share.user.name 
    }; 
}); 

HTML : 제 2 제어부 사용의

<div ng-controller="MainCtrl"> 
    <input ng-model="user.name" />  
</div> 
<div ng-controller='linctr'> 
    <div>{{super.name}}</div> 
</div> 

답변

1

: $scope.supershare.user 같은 객체 이때

.controller('linctr', function($scope, share) { 
    $scope.super = share.user;    
}); 

. 당신이

$scope.super = { 
    name: share.user.name 
}; 

supershare.user 객체에 연결하지 못 할 경우 그렇지 않은 단지의 특성 name의 프리미티브 값을 할당합니다.

+0

감사합니다. 그러나 작동하지 않았습니다 .... – linyuanxie

+0

방금 ​​controllerA에 $ watch를 추가했는데 작동했습니다! $ scope. $ watch ('user.name', function (newv, oldv) { share. user.name = newv; console.log (share.user.name);}); } – linyuanxie

+0

예, 방금 $ watch에 조언하고 싶습니다. 또 다른 방법은 첫 번째 컨트롤러에서'share.user = $ scope.user; '를 사용하는 것입니다. http://plnkr.co/edit/S2vdNVFOT6BkFSEJuLQK?p=preview – dfsq

관련 문제