简体   繁体   English

使用AngularJS工厂在控制器之间共享数据

[英]Sharing data with between Controllers with a Factory, AngularJS

I want to share data between controllers: 我想在控制器之间共享数据:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.4/angular.min.js"></script>
<script>
var myApp = angular.module('myApp',[]);
myApp.factory('Data', function(){
    return {show: true, text: "Hello"};
});

myApp.controller('ctrl1', ['$scope', 'Data', function($scope, Data) {
    $scope.data = Data;
}]);

myApp.controller('ctrl2', ['$scope', 'Data', function($scope, Data) {
    $scope.click = function(){
      Data = {text:"Hello2", show:true};
    }
}]);
</script>
<body ng-app='myApp'>
<div style="background-color:red;margin-top:30px;" ng-controller="ctrl1">
    {{data.text}}
</div> 
<div style="background-color:yellow;margin-top:30px;" ng-click="click()" ng-controller="ctrl2">
    Click to change data
</div> 
</body>

Demo http://plnkr.co/edit/QHuWLYjBqDvl20fL7eeu?p=preview . 演示http://plnkr.co/edit/QHuWLYjBqDvl20fL7eeu?p=preview This doesn't work, however if I write 这不起作用,但是如果我写

Data.text = 'Hello2';
Data.show = true;

It works perfectly. 它运作完美。 Demo http://plnkr.co/edit/xKtLUlBu0dQPUsiNCRyC?p=preview 演示http://plnkr.co/edit/xKtLUlBu0dQPUsiNCRyC?p=preview

It would be very handy to just updating a model by just specifying Json, how can I do it? 仅通过指定Json来更新模型将非常方便,我该怎么做?

By doing Data = {text:"Hello2", show:true}; 通过执行Data = {text:"Hello2", show:true}; you completely overwrite initial Data object, which results into broken reference. 您将完全覆盖初始的Data对象,从而导致引用损坏。 That's why you can't just assign completely new object. 这就是为什么您不能只分配全新的对象。 You however can do it something like this: 但是,您可以执行以下操作:

myApp.factory('Data', function(){
    return {
        prop: {show: true, text: "Hello"}
    };
});

and later: 然后:

Data.prop = {text: "Hello2", show: true};

When you write 当你写

Data = {text:"Hello2", show:true};

You are overwriting the local Data variable with a new local object 您正在用新的本地对象覆盖本地Data变量

When writing 写作时

Data.text = 'Hello2';
Data.show = true;

The original object that is also linked in parent scopes remains, you are overwriting variables inside the Data object instead of just overwriting the local Data link to the object 仍然在父作用域中链接的原始对象仍然保留,您正在覆盖Data对象中的变量,而不仅仅是覆盖指向该对象的本地Data链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM