如何与服务控制器之间的共享和更新数据angularjs [英] how to sharing and update data between controller with service in angularjs

查看:142
本文介绍了如何与服务控制器之间的共享和更新数据angularjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我想与工厂控制器之间的数据共享。我要的是每当我更新controlA在controlB值将被更新我的输入值。请你指出哪里是我的问题?

  VAR应用= angular.module('应用',[]);
app.factory('份额',函数(){
    返回{
        用户:{}
    };
})
.controller('MainCtrl',函数($范围,股){
    $ scope.user = {
        名称:'林'
    };
    share.user.name = $ scope.user.name;
    的console.log(share.user.name);
})
.controller('linctr',函数($范围,股){
    $ scope.super = {
        名称:share.user.name
    };
});

HTML:

 < D​​IV NG控制器=MainCtrl>
    <输入NG模型=user.name/>
< / DIV>
< D​​IV NG控制器='linctr'>
    < D​​IV> {{super.name}}< / DIV>
< / DIV>


解决方案

在第二个控制器使用方法:

  .controller('linctr',函数($范围,股){
    $ scope.super = share.user;
});

在这种情况下, $ scope.super 指向同一个对象 share.user 。否则,当你做

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

超级 share.user 对象没有任何连接,它只是分配财产<$的原始值C $ C>名称。

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>

解决方案

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.

这篇关于如何与服务控制器之间的共享和更新数据angularjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆