javascript - 在 View 中保存表单数据

标签 javascript angularjs angularjs-scope ng-view route-provider

如何在 AngularJS 中将数据从一个 View 保存到另一个 View ?

我做了$rootScope

最佳答案

据我所知,每个 View 使用 2 个不同的 Controller (或者一个用于 View ,一个用于 Root View )。

问题是 Angular 无法在 Controller 之间共享数据。

您要么必须使用服务/工厂,要么使用 rootscope,但不是像您那样,而是使用 broadcastemit

如果我是你,我会使用一项服务。

编辑给您,为您提供的服务:

(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/

相关文章:

javascript - extjs 中的 refs 是被覆盖还是被继承?

javascript - MongoDB Cursor 没有方法 'next'

javascript - 如何使用 Angularjs 显示数据?

javascript - AngularJS $resource GET 中的多个参数

javascript - Angular 与 Browserify

javascript - Angular 在启用 html5mode 时出现错误 : $rootScope:infdig Infinite $digest Loop

javascript - 将复杂的Javascript对象传递给ASP.NET Web服务

javascript - 我如何知道 Google Apps 用户是否不是管理员?

javascript - 在 AngularJS 中,$scope 变量值无法在 $http 成功回调之外访问

Angularjs:$scope.variable与 View 不同步?