保存视图中的表单数据

Save form data in view

本文关键字:表单 数据 视图 保存      更新时间:2023-09-26

我如何保存数据从一个视图到另一个在angularjs?

i did $rootScope

在我看来,你为每个视图使用了2个不同的控制器(或者一个用于视图,一个用于根视图)。

问题是Angular不能在这样的控制器之间共享数据。

您要么必须使用服务/工厂,要么使用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;
    }
}
})();

这将存储变量。在您的控制器中,您添加CountriesService作为依赖项,保存您使用CountriesService.setCountries,加载您使用CountriesService.getCountries。请注意,刷新页面将删除所有数据!

EDIT NUMBER 2如果你害怕John papa指南,这里有一个简单的服务,你可以在你放置控制器的同一个文件中使用:

    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;
        }
    });

我有一个或多或少做到这一点的应用程序。一个服务很好地解决了这个问题,并创建了一种机制,这样你就可以在应用程序的任何地方这样做。

首先,我建议不要尝试用作用域来管理它。只需在控制器上放置一个对象(myFormObj),并添加您想要的属性(名称,排名,序列号等)。

然后将表单的输入字段绑定到该对象中的属性(与作用域变量相反)。你的ng-model会像myctl。formobj。name等等。

当用户触发改变视图的事件时,将该formObj的COPY (angular.copy)保存到旁边,通常在服务中(如FormStateService或其他东西)。FormStateService只能保存一个简单的数组。

this.forms = { 'TheNameOfYourForm' : theFormObjToSave };

因此,当用户触发离开表单的事件时,您只需这样做:

formStateSvc。forms ['NameOfMyForm'] = angular。

当用户返回到原始视图并且控制器初始化时,你只需询问formStateSvc:

if ( 'NameOfMyForm' in formStateSvc.forms ) {
   this.formObj = formStateSvc.forms [ 'NameOfMyForm' ];
}

瞧,您的旧表单状态恢复了。

更健壮,你可以创建"addForm, removeForm"方法等,你可以确保对未定义的东西,你可以使重新绑定到前状态隐式(当你的表单的控制器初始化,只是要求它恢复状态,如果有任何恢复)。所以你的控制器会有:

。formObj = formStateSvc。rebindOldDataIfItExists ('MyFormName');

你懂的。

一个简单的方法是创建一个值提供者对象并将其发布到作用域:

//Create value provider object
app.value("FormObj", {});
app.controller("myController", function($scope, FormObj) {
    //Publish on scope
    $scope.FormObj = FormObj;
});

然后让ng-model指令使用该对象:

Name <input ng-model="FormObj.name"><br>
Rank <input ng-model="FormObj.rank"><br>
SerialNum <input ng-model="FormObj.ssnum"><br>

value对象是一个在应用程序生命周期中持续存在的单例对象。对对象内容的更改将被保留,并可供其他控制器使用,并且在视图更改后仍然有效。

PLNKR的DEMO