出于某种原因,当我更新出厂值时,关联的视图不会更新。我绑定到服务中的对象而不是字符串,所以我不知道我做错了什么,但实施上肯定有问题。我为了简洁而减少了代码,并将其添加到了一个plunker中。我以为我过度搞砸了服务,但显然没有。我甚至再次阅读article以确保我认为我理解的是正确的。
首次获取标题的价值,您会看到“欢迎!”#39;在标题中,但之后它不会更新为“上一个下一个!”。
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>
答案 0 :(得分:1)
setTimeout
是一个事件,它不会让角度上下文中发生变化的角度作为在角度上下文之外运行的自定义事件。在这种情况下,摘要周期不会起火,您需要手动运行它。
理想情况下,您应该使用与$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);