gpt4 book ai didi

javascript - 问题绑定(bind)/监视两个 Controller 之间共享的服务变量

转载 作者:行者123 更新时间:2023-11-29 17:15:44 25 4
gpt4 key购买 nike

我很难理解这里发生了什么。我了解 Angular 的 $digest 循环的基础知识,并且根据 this SO post ,我通过简单地将作用域变量分配给服务的属性(在本例中为数组)来正确地做事。如您所见,我可以更新 CtrlA 的“事物”的唯一方法是在我使用新数组的引用更新我的服务属性后重新分配它。

这是一个说明我的问题的 fiddle :

http://jsfiddle.net/tehsuck/Mujun/

(function () {
angular.module('testApp', [])
.factory('TestService', function ($http) {
var service = {
things: [],
setThings: function (newThings) {
service.things = newThings;
}
};
return service;
})
.controller('CtrlA', function ($scope, $timeout, TestService) {
$scope.things = TestService.things;
$scope.$watch('things.length', function (n, o) {
if (n !== o) {

alert('Things have changed in CtrlA');
}
});
$timeout(function () {
TestService.setThings(['a', 'b', 'c']);

// Without the next line, CtrlA acts like CtrlB in that
// it's $scope.things doesn't receive an update
$scope.things = TestService.things;
}, 2000);
})
.controller('CtrlB', function ($scope, TestService) {
$scope.things = TestService.things;
$scope.$watch('things.length', function (n, o) {
if (n !== o) {
// never alerts
alert('Things have changed in CtrlB');
}
});
})

})();

最佳答案

您的代码有两个问题:

  1. 数组没有count 属性;您应该改用 length

    $scope.$watch('things.length', ...);

    但有一个警告:如果您向 things 数组添加元素或从中删除元素,并最终得到一个长度相同的不同列表,则不会触发观察者回调。

  2. TestServicesetThings 方法将对things 数组的引用替换为一个新数组,使TestService. things 指向内存中的一个新数组,而 CtrlA.$scope.thingsCtrlB.$scope.things 仍然指向旧数组,即空的。以下代码说明了这一点:

    var a = [];
    var b = a;

    a = [1, 2, 3];
    console.log(a); // prints [1, 2, 3];
    console.log(b); // prints [];

    因此,为了让您的代码正常工作,您需要更改 TestService.setThings 更新其 things 数组的方式。这是一个建议:

    setThings: function (newThings) {
    service.things.length = 0; // empties the array
    newThings.forEach(function(thing) {
    service.things.push(thing);
    });

这是一个 working version你的 jsFiddle。

关于javascript - 问题绑定(bind)/监视两个 Controller 之间共享的服务变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18300459/

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