gpt4 book ai didi

javascript - 通过服务在 Controller 之间同步数据

转载 作者:数据小太阳 更新时间:2023-10-29 05:44:22 26 4
gpt4 key购买 nike

来自 this stackoverflow question ,我的理解是我应该使用服务在 Controller 之间传递数据。

但是,如 my example JSFiddle 中所示,当跨 Controller 修改我的服务时,我无法收听它的变化。

angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.status = App.data.status;
$scope.$watch('App.data.status', function() {
$scope.status = App.data.status;
});
})
.controller('Ctrl2', function ($scope, App) {
$scope.status = App.data.status;
$scope.$watch('status', function() {
App.data.status = $scope.status;
});
})
.service('App', function () {
this.data = {};
this.data.status = 'Good';
});

在我的示例中,我尝试在 Ctrl1 中订阅 App.data.status,并尝试从 Ctrl1 发布数据> 到 App。但是,如果您尝试更改与 Ctrl2 关联的 div 中的输入框,则文本不会跨 Controller 边界更改为 Ctrl1 .

最佳答案

http://jsfiddle.net/VP4d5/2/

这是一个更新的 fiddle 。基本上,如果您要在服务的两个 Controller 之间共享相同的数据对象,您只需要使用字符串或 javascript 原语之外的某种对象。在这种情况下,我只是使用常规对象 {} 在两个 Controller 之间共享数据。

JS

angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.localData1 = App.data;
})
.controller('Ctrl2', function ($scope, App) {
$scope.localData2 = App.data;
})
.service('App', function () {
this.data = {status:'Good'};
});

HTML

<div ng-controller="Ctrl1">
<div> Ctrl1 Status is: {{status}}
</div>
<div>
<input type="text" ng-model="localData1.status" />
</div>
<div ng-controller="Ctrl2">Ctrl2 Status is: {{status}}
<div>
<input type="text" ng-model="localData2.status" />
</div>
</div>

在这里使用服务没有错,但如果唯一的目的是在应用程序中共享对象,那么我认为使用 .value 更有意义。如果此服务将具有与端点和数据交互的功能,请务必使用 angular.copy 来更新对象属性,而不是使用 =,这将替换服务的本地引用,但不会反射(reflect)在 Controller 中。

http://jsfiddle.net/VP4d5/3/

使用.value修改后的JS

angular.module('myApp', [])
.controller('Ctrl1', function ($scope, sharedObject) {
$scope.localData1 = sharedObject;
})
.controller('Ctrl2', function ($scope, sharedObject) {
$scope.localData2 = sharedObject;
})
.value("sharedObject", {status:'Awesome'});

关于javascript - 通过服务在 Controller 之间同步数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20434767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com