由于某些原因,当我更新工厂值时,关联的视图不会更新。我绑定到服务中的一个对象,而不是字符串,所以我看不出我做错了什么,但实现肯定有问题。为了简洁起见,我减少了代码,并将其添加到了一个plunker中。我以为我把服务搞砸了,但显然不是。我甚至重新阅读了这篇文章,以确保我认为我理解的是正确的。
标题的值是第一次提取的,您会看到"欢迎!"在标题中,但之后它不会更新为"下一个!"。
https://plnkr.co/edit/ma1SDJyIKoFPWznXdxTO?p=preview
<!DOCTYPE html>
<html ng-app="app">
<head>
<html-title></html-title>
</head>
<body>
<main></main>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>
(function () {
'use strict';
function MainController(HtmlTitleFactory) {
HtmlTitleFactory.set('Welcome!'); // title gets set
// check title was changed
this.data = HtmlTitleFactory.get();
setTimeout(function() {
// updates title
HtmlTitleFactory.set('Up Next!');
// title looks to be set, but changes not picked up in view
console.log(HtmlTitleFactory.get());
}, 3000);
}
MainController.$inject = [
'HtmlTitleFactory'
];
var main = {
template: '<div>{{ vm.data.title }}</div>',
controller: MainController,
controllerAs: 'vm'
};
////////////////////////////
function HtmlTitleController(HtmlTitleFactory) {
var vm = this;
//vm.title = HtmlTitleFactory.get().title;
vm.title = HtmlTitleFactory.get();
}
HtmlTitleController.$inject = [
'HtmlTitleFactory'
];
var htmlTitle = {
template: '<title>{{ vm.title.title }}</title>',
controller: HtmlTitleController,
controllerAs: 'vm'
};
////////////////////////////
function HtmlTitleFactory() {
var service = {
title: 'Default'
};
function set(title) {
// originally tried this since bound to object this should work
// service.title = title;
// wasn't working so tried this as well
angular.extend(service, {
title: title
});
}
function get() {
return service;
}
return {
set: set,
get: get
};
}
HtmlTitleFactory.$inject = [];
////////////////////////////
angular
.module('app', [])
.component('main', main)
.component('htmlTitle', htmlTitle)
.factory('HtmlTitleFactory', HtmlTitleFactory);
})();
</script>
</body>
</html>
setTimeout
是一个事件,它不会告诉angular在角度上下文中发生了更改,因为它是在角度上下文之外运行的自定义事件。在这种情况下,摘要循环不会着火,您需要手动运行它。
理想情况下,您应该使用$timeout
,它的工作原理与setTimeout
类似,并且在触发回调时运行摘要循环。
$timeout(function() {
HtmlTitleFactory.set('Up Next!'); // update title
console.log(HtmlTitleFactory.get()); // title looks to be set but not picked up in view
}, 3000);
Plunkr