我有一个工厂,“itemData”,它拥有一项服务。
app.factory('itemData', function () {
var itemData = {
Title: 'I should be different',
getTitle: function () {
return itemData.Title;
},
setTitle: function (title) {
return itemData.Title=title;
},
// This is the function to call all of the sets for the larger object
editItem: function (entry)
{
itemData.setTitle(entry);
}
};
return itemData;
});
我有2个控制器(在不同的文件中)与2个独立的视图相关联。 第一个:
// IndexCtrl
app.controller("IndexCtrl", ['$scope','$window','itemData',
function($scope, $window, itemData) {
var entry = "I'm different";
// After a submit is clicked
$scope.bttnClicked = function (entry) {
itemData.editItem(entry);
console.log(itemData.getTitle(); //<--itemData.Title has changed
// moves to page with other controller
$window.location.href = "edit.html";
};
}
]);
和第二个,它没有做我想要的事情:
app.controller("editItemCtrl", ['$scope', '$window', 'itemData',
function ($scope, $window, itemData){
$scope.item = {
"Title": itemData.getTitle(), //<--- Title is "I should be different"
}
}]);
答案 0 :(得分:3)
你的Angular应用程序中是否有某种路由器?当您更改位置href时,它是否实际导致整页重新加载?
服务保存在内存中,因此不会在页面重新加载时保持状态。
答案 1 :(得分:0)
我认为表达式是[&#39; $ scope&#39;,&#39; $ window&#39;,&#39; itemData&#39;, function($ scope,$ window,itemData)强制初始化依赖注入,因此你有两个不同的对象。
如果您看到文档https://docs.angularjs.org/guide/controller,则在本节中有一个名为设置$ scope对象的初始状态的部分描述了范围,但我认为可以在服务列表中进行扩展在[...]甚至在angular.module(moduleName,[...])中,如果[....]被填充,功能区返回一个新模块并且仅用于空方括号返回当前模块实例< / p>
我认为这可以帮助你