javascript - 使用 AngularJS 将表单数据数组保存到先前的数组

标签 javascript arrays angularjs

我的 script.js 中有一个数组,例如:

 $scope.companies = [
        {
            id: '1',
            contact: 'John',
            address: 'Some street, United States',
            function: 'Client',
            telephone: '0123455858446',
            fax: '0128289385',
            url: 'http://www.example.com'
        },

    ];

然后有一个表单可以将新项目添加到数组中 - 提交表单后,它会创建自己的数组项目,然后将其“推送”到旧数组中。

console.log 然后打印出完整的数组,其中包含所有数据。

但是,如果我随后浏览到另一个页面,在其中显示表中的数据,则不会显示它 - 并且它尚未将数组项添加到 script.js。

我该如何解决这个问题?

script.js:

    // Define a new module for our app
var app = angular.module("myApp", ['ngRoute', 'UserApp']);
var appName = 'My App';

// Config the route
app.config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider) {
        $routeProvider.
        when('/', {
            templateUrl: 'dashboard.html',
            controller: 'DashboardController',
            public: false
        }).
        when('/companies', {
            templateUrl: 'companies.html',
            controller: 'CompaniesController',
            public: false
        }).
        when('/companies/add', {
            templateUrl: 'add-company.html',
            controller: 'CompaniesController',
            public: false
        }).
        when('/login', {
            templateUrl: 'login.html',
            controller: 'LoginController',
            login: true
        }).
        when('/management/create-user', {
            templateUrl: 'management/create-user.html',
            public: false
        }).
        when('/account/edit/:userid', {
            templateUrl: 'account/edit.html',
            controller: 'EditAccountController',
            public: false
        }).
        when('/profile/:userid', {
            templateUrl: 'account/profile.html',
            controller: 'ProfileController',
            public: false
        }).
        otherwise({
            templateUrl: '404.html'
        });
        $locationProvider.html5Mode(true);
    }]);

app.run(function(user) {
    user.init({ appId: 'REMOVED' });
});

app.controller("DashboardController", function($scope) {
    $scope.title = 'Dashboard';
});

app.controller("CompaniesController", ['$scope', function($scope) {
    $scope.title = 'Companies';
    $scope.title_sub = 'Add Company';

    $scope.add = function(newCompany) {
        $scope.companyData = [
            {
                id: newCompany.id,
                primary_contact: newCompany.primary_contact,
                address: newCompany.address,
                function: newCompany.function,
                telephone: newCompany.phone,
                fax: newCompany.fax,
                url: newCompany.url
            }
            ];
        console.log(newCompany);
        console.log($scope.companyData);
        console.log($scope.companies);
        $scope.companies.push.apply($scope.companies, $scope.companyData);
    };

    $scope.companies = [
        {
            id: '1',
            contact: 'John',
            address: 'Some street, United States',
            function: 'Client',
            telephone: '0123455858446',
            fax: '0128289385',
            url: 'http://www.example.com'
        },
    ];
}]);

app.controller('GlobalController', ['$scope', function($scope) {
        $scope.appName = "My App";
    }]);

app.controller("LoginController", function($scope) {
    $scope.title = 'Login';
});

app.controller('EditAccountController', ['$scope' ,'$routeParams', function($scope, $routeParams) {
    $scope.title = 'Edit Account';
    $scope.update = function(userAccount) {
        UserApp.User.save({
            "user_id": $routeParams.userid,
            "first_name": userAccount.first_name,
            "last_name": userAccount.last_name,
            "email": userAccount.email,
            "properties": {
                "phone": userAccount.phone
            }
        }, function (error, result) {
            if (result) {
                $scope.$apply(function () {
                    $scope.saveUser = 'Your account has been updated.';
                })
            } else if (error) {
                $scope.saveUser = "Something went wrong. Please try again!";
            }
            else {
                $scope.saveUser = "Something went wrong. Please try again!";
            }
        });
    }
}]);

app.controller('ProfileController', ['$scope', '$routeParams',  function($scope, $routeParams) {
    $scope.title = 'Profile';
    UserApp.User.get({
        "user_id": $routeParams.userid
    }, function(error, result){
        // Handle error/result
        if (result) {
            $scope.$apply(function(

            ) {
                $scope.getUser = result[0]
            })
        } else if (error) {
            $scope.getUser = error
        }
    });
}]);

add-company.html:

<div class="row">
    <div class="col-md-12">
        <h1>{{ title_sub }}</h1>
    </div>

</div>

<div class="row">
    <div class="col-md-12">
        <p>Add a new company.</p>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <form>
            <div class="form-group">
                <label>ID</label><input type="text" name="id" id="id" ng-model="newCompany.id" tabindex="1" class="form-control">
                <label>Primary Contact</label><input type="text" name="primary_contact" id="primary_contact" tabindex="2" ng-model="newCompany.primary_contact" class="form-control">
                <label>Address</label><input type="text" name="address" id="address" tabindex="2" ng-model="newCompany.address" class="form-control">
                <label>Function</label><input type="text" name="function" id="function" tabindex="2" ng-model="newCompany.function" class="form-control">
                <label>Telephone</label><input type="text" name="telephone" id="telephone" tabindex="2" ng-model="newCompany.phone" class="form-control">
                <label>Fax</label><input type="text" name="fax" id="fax" tabindex="2" ng-model="newCompany.fax" class="form-control">
                <label>URL</label></lab><input type="text" name="url" id="url" tabindex="2" ng-model="newCompany.url" class="form-control">
            </div>
            <div class="form-group">
                <div class="row">
                    <div class="col-sm-6 col-sm-offset-3">
                        <input type="submit" name="add-submit" id="add-submit" tabindex="10" ng-click="add(newCompany)" class="form-control btn btn-primary" value="Add Company">
                        <br>
                        <div class="text-center">
                            <p ng-show="addCompany"><span class="label label-info">{{ addCompany }}</span></p>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

编辑:新 Controller :

app.controller("CompaniesController", ['$scope', 'companyService', function($scope, companyService) {
    $scope.title = 'Companies';
    $scope.title_sub = 'Add Company';

   $scope.add = function(newCompany) {
       companyService.addCompany( {
           id: newCompany.id,
           primary_contact: newCompany.primary_contact,
           address: newCompany.address,
           function: newCompany.function,
           telephone: newCompany.phone,
           fax: newCompany.fax,
           url: newCompany.url
       });
    };

    $scope.companies = companyService.getCompanies();

}]);

最佳答案

使用服务的示例,您必须在每个 Controller 中“注入(inject)”服务,就像我在 EditAccountController 中所做的那样

app.service('companyService',[function(){
     var companies = [];
     return {
         addCompany: function(company){
            companies.push(company);
         },
         getCompanies: function(){ 
               return companies;
         }
     }
}]);

app.controller('EditAccountController', ['$scope', 'companyService', function($scope, companyService){

 $scope.companies = companyService.getCompanies();
}]);

关于javascript - 使用 AngularJS 将表单数据数组保存到先前的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33673559/

相关文章:

javascript - 如何在 Linux Web 服务器上运行 Phantomjs

javascript - Bootstrap : Header moves when modal opens

arrays - 如何演示数组上的竞争条件

TCL 中的类 C 数组

c++ - 在函数中创建的 C++ 数组的行为

javascript - jQuery 单击事件仅在第二次单击后才有效

javascript - 谷歌图表显示所有标签

angularjs - 从 AngularJs http web api 请求重定向到 Identity Server 登录页面

angularjs - 在AngularJS中设置JSONP回调函数

javascript - 将日期转换为类似于 JavaScript 中的 Date.now() 格式