如何在 AngularJS 中将数据从一个 View 保存到另一个 View ?
我做了$rootScope
最佳答案
据我所知,每个 View 使用 2 个不同的 Controller (或者一个用于 View ,一个用于 Root View )。
问题是 Angular 无法在 Controller 之间共享数据。
您要么必须使用服务/工厂,要么使用 rootscope,但不是像您那样,而是使用 broadcast
和 emit
如果我是你,我会使用一项服务。
编辑给您,为您提供的服务:
(function() {
'use strict';
angular
.module('YourModuleName')
.factory('CountriesService', CountriesService);
CountriesService.$inject = ['Your', 'dependencies', 'here', 'in', 'string'];
/* @ngInject */
function CountriesService(your, dependencies, here, not, in, string) {
var service = {
setCountries: setCountries,
getCountries: getCountries
};
var vm = this;
vm.countries = []; // Or maybe an object ?
// ... List of other variables you need to store.
return service;
////////////////
function setCountries(listOfCountries) {
vm.countries = listOfCountries;
}
function getCountries() {
return vm.countries;
}
}
})();
这将存储您的变量。在您的 Controller 中,您添加 CountriesService
作为依赖项,以保存您使用 CountriesService.setCountries
并加载您使用 CountriesService.getCountries
。请注意,刷新页面将删除所有数据!
编辑数字 2 如果你害怕John papa guidelines ,这是一个简单的服务,您可以在放置 Controller 的同一文件中使用:
app.factory('CountryControl', function(your, dependencies) {
var service = {
setCountries: setCountries,
getCountries: getCountries
};
this.countries = []; // Or maybe an object ?
// ... List of other variables you need to store.
return service;
////////////////
function setCountries(listOfCountries) {
this.countries = listOfCountries;
}
function getCountries() {
return this.countries;
}
});
关于javascript - 在 View 中保存表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40529520/