Reputation: 787
Now I am trying sharing data between controllers with factory. what I want is whenever I update my input value in controlA the value in controlB will be updated. Would you please point out where is my problem?
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:
<div ng-controller="MainCtrl">
<input ng-model="user.name" />
</div>
<div ng-controller='linctr'>
<div>{{super.name}}</div>
</div>
Upvotes: 1
Views: 693
Reputation: 193261
In the second controller use:
.controller('linctr', function($scope, share) {
$scope.super = share.user;
});
In this case $scope.super
points to the same object as share.user
. Otherwise when you do
$scope.super = {
name: share.user.name
};
super
has no connection to share.user
object, it just assigns primitive value of the its property name
.
Upvotes: 1