how to sharing and update data between controller with service in angularjs

ぃ、小莉子 提交于 2019-12-11 11:43:19

问题


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:


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.



来源:https://stackoverflow.com/questions/27534822/how-to-sharing-and-update-data-between-controller-with-service-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!