gpt4 book ai didi

javascript - 从 Controller 观察服务的变化

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

我正在尝试监听 Controller 中注入(inject)服务( self 更新)的变化。在下面的示例中,您会发现两种 $watch 情况 - 一种有效但我不知道确切原因,另一种对我来说很明显但不起作用。第二个例子是正确的方法吗?那不是重复代码吗?正确的做法是什么?

服务:

app.factory("StatsService", [
'$timeout', 'MockDataService',
function ($timeout, MockDataService) {
var service, timeout;
timeout = 5000;
service = {
fetch: function () {
// Getting sample data, irrelevant, however this is what updates the data
return this.data = MockDataService.shuffle();
},
grab: function () {
this.fetch();
return this.update();
},
update: function () {
var _this = this;
return $timeout(function () {
return _this.grab();
}, timeout);
}
};
service.grab();
return service;
}
]);

Controller :

app.controller("StatsController", [
'$scope', 'StatsService',
function ($scope, StatsService) {
var chart;
$scope.stats = StatsService;
$scope.test = function (newValue) {
if (arguments.length === 0) {
return StatsService.data;
}
return StatsService.data = newValue;
};

// This doesn't work
$scope.$watch('stats', function (stats) {
return console.log('meh');
});

// This works, don't know why
$scope.$watch('test()', function (stats) {
return console.log('changed');
});
}
]);

最佳答案

$watch见第三个参数: objectEquality

Compare object for equality rather than for reference.

但是,如果您只对观察返回的数据感兴趣,那么您应该这样做:

$scope.$watch('stats.data', function (stats) {
return console.log('meh');
});

关于javascript - 从 Controller 观察服务的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18360809/

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