1

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>

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I just added $watch in controllerA,then it works!$scope.$watch('user.name',function(newv,oldv){ share.user.name=newv; console.log(share.user.name); }); })
Yes, I just wanted to advise $watch. Or another approach is to use share.user = $scope.user; in the first controller. plnkr.co/edit/S2vdNVFOT6BkFSEJuLQK?p=preview
But you are right, I should point to object instead of property.Thank you for pointing out.
It's better to avoid additional watchers for performance sake. So if you can use object references it's more natural for javascript, as it works very fast.
I see it, Thank you very much for helping me out. it is real helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.