简体   繁体   English

在AngularJS的控制器中将对象保存到数组中

[英]Saving an object into an array in a controller in AngularJS

I've been creating a contact list website and have just begun trying to implement an add contact function. 我一直在创建联系人列表网站,并且刚刚开始尝试实现添加联系人功能。 So far I have created the page using a form and input elements and then use ng-click to call a function which theoretically would add an object containing these input values into an already-existing array in the controller. 到目前为止,我已经使用表单和输入元素创建了页面,然后使用ng-click调用了一个函数,该函数理论上会将包含这些输入值的对象添加到控制器中已经存在的数组中。 For some reason this doesn't work and nothing is added. 由于某种原因,这不起作用,并且没有添加任何内容。

In particular, I'm having trouble with the js/app.js file and the $scope.saveContact = function() in relation to the partial/edit.html webpage. 特别是,我在js / app.js文件和$ part。/ edit.html网页的$ scope.saveContact = function()方面遇到了麻烦。 Clicking the "Confirm button" when trying to add a contact calls the saveContact function, but the results are not stored properly. 尝试添加联系人时单击“确认按钮”会调用saveContact函数,但结果存储不正确。 Any help is appreciated. 任何帮助表示赞赏。

In my HTML I have this code (which calls the saveContact() function in my controller. 在我的HTML中,我有以下代码(该代码在我的控制器中调用saveContact()函数。

<a href="#/"><div class="confirm col-xs-6" ng-click="saveContact()">
    <h3>Confirm</h3>
</div></a>

In my app.js file I have a declaration of an empty object and an array containing objects that already have values (used to display the contacts that are already created). 在我的app.js文件中,我有一个空对象的声明和一个包含已具有值的对象的数组(用于显示已创建的联系人)。 I'm trying to add to these contacts using .push() but it for some reason it doesn't work. 我正在尝试使用.push()添加到这些联系人,但是由于某种原因,它无法正常工作。

$scope.contact = { ... } //empty object that gets inputs from HTML
$scope.contacts = [ { ... }, ... ];
$scope.saveContact = function(){
    $scope.contacts.push($scope.contact);
};

This bottom function fails to push the contact object to the contacts array and I don't understand why. 此底部函数无法将联系人对象推送到联系人数组,我不明白为什么。

This is happening as you have assigned same controller to all your routes. 这是因为您为所有路由分配了相同的控制器。 Your saveContact function is working fine, its pushing the object to the array. 您的saveContact函数可以正常工作,它将对象推入数组。 As soon as the route changes, a new instance of the controller is created and hence the added object is lost. 更改路线后,将立即创建控制器的新实例,因此丢失添加的对象。 You should create a service(singleton) to store the object and inject the service as a dependency to the controller. 您应该创建一个服务(单个)来存储对象,并将该服务作为对控制器的依赖项注入。 In this way the array will persist until the page load. 这样,数组将一直保留到页面加载为止。

app.service("storeContact", function(){
  var contacts = [];

  this.setContact = function(cnt){
    contacts.push(cnt)
  };

  this.getContact = function(){
    return contacts;
  }
});

And inject it in the controller and use the setContact and getContact methods to update the contact array and retrieve the contact array. 并将其注入控制器中,并使用setContact和getContact方法更新联系人数组并检索联系人数组。

Ideally, you should have separate controllers for your route. 理想情况下,您应该为自己的路线设置单独的控制器。

The issue is in your app.config code. 问题出在您的app.config代码中。 You are using the same controller for all your templates. 您对所有模板都使用相同的控制器。

This is not required since you have already mentioned the same in ng-controller attached with body 这不是必需的,因为您已经在与body相连的ng-controller提到了相同的内容

  <body ng-controller="AppController">
    <div ng-view></div>
    <script src="js/app.js"></script>
  </body>

Using same controller for all your routes is essentially (re)instantiating the controllers when the route is changed and thats the reason why $scope.contacts.push($scope.contact); 对所有路径使用相同的控制器实质上是在更改路径时(重新)实例化控制器 ,这就是$scope.contacts.push($scope.contact);的原因$scope.contacts.push($scope.contact); is ineffective for the route / when called from /add . /add调用时,对路由/无效。

contactListApp.config(['$routeProvider', '$locationProvider',
  function($routeProvider, $locationProvider) {
    $routeProvider
      .when('/', {
        controller: 'AppController',
        controllerAs: 'list',
        templateUrl: 'partials/list.html'
      })
       .when('/add', {
        controller: 'AppController',
        controllerAs: 'add',
        templateUrl: 'partials/edit.html'
      })
       .when('/edit/:id', {
        controller: 'AppController',
        controllerAs: 'edit',
        templateUrl: 'partials/edit.html'
      })
      .otherwise({
        redirectTo: '/'
      });
}]);

Workaround: 解决方法:

Either use separate controllers for separate routes and use a service to store the object 将单独的控制器用于单独的路由,或者使用服务来存储对象

OR 要么

Simply remove the controller and controller as from your route config and you are good to go. 只需从路由配置中删除控制器和控制器即可,一切顺利。

Updated config: 更新的配置:

contactListApp.config(['$routeProvider', '$locationProvider',
  function($routeProvider, $locationProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'partials/list.html'
      })
       .when('/add', {
        templateUrl: 'partials/edit.html'
      })
       .when('/edit/:id', {
        templateUrl: 'partials/edit.html'
      })
      .otherwise({
        redirectTo: '/'
      });
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM