将对象插入数组

时间:2017-12-01 13:49:36

标签: angularjs

我创建了一个假的App来测试AngularJs。我使用localStorage和ngStorage。 我的问题是我不能在数组中放入带数据的对象。 当我尝试,我有一个我不明白的错误信息:

"Error: vendeursList.push is not a function [etc...]"

这是我的代码:

HTML:

<div ng-controller='vendeursController'>
<h2 class='test'>Vendeurs.</h2>
<table>
    <thead>
      <tr><th colspan="4">Liste des vendeurs</th></tr>
    </thead>
    <tbody>
      <tr ng-repeat="vendeur in objVendeur">
        <td>{{$index + 1}}</td>
        <td>
          {{vendeur.Vendeur.nom}}&nbsp;{{vendeur.Vendeur.prenom}}
        </td>
        <td>{{vendeur.mail}}</td>
        <td>{{vendeur.adresse}}</td>
      </tr>
    </tbody>
</table>

<form class='simple-form'>
    <br>
    <input type="text" ng-model="vendeur.Vendeur.nom" name="nom" value="Nom" required><br>
    <br>
    <input type="text" ng-model="vendeur.Vendeur.prenom" name="prenom" value="Prenom" required><br><br>
    <br>
    <input type="text" ng-model="vendeur.mail" name="mail" value="Mail" required><br><br>        
    <br>
    <input type="text" ng-model="vendeur.adresse" name="adresse" value="Adresse" required><br><br>
    <input ng-click="saveData()" type="submit" value="Submit">
</form>

<pre>nom = "{{vendeur | json}}"</pre>

JS:

(function() {
  'use strict';

angular.module('app.vendeurController', ["ngStorage"]).
controller('vendeursController', function($scope, $http, $localStorage){

    $scope.vendeur = {};
    var vendeursList = [];

    $scope.saveData = function() {
        vendeursList = $localStorage.objVendeur;
        var nVendeur = angular.copy($scope.vendeur);
        vendeursList.push(nVendeur);
        $localStorage.objVendeur = vendeursList;
    }

});
})();

谢谢!

2 个答案:

答案 0 :(得分:3)

您应该使用userSchema.pre('update', function(next) { if (this._conditions) { _id = this._conditions.id || ''; User.findOne({ id : _id }).exec().then((user) => { if (user.token === undefined) { this._update['$set'].token = 'some token'; next(); } }); } next(); }); JSON.stringify来获取和设置localStorage中的项目。你可以使用类似的东西 -

JSON.parse

另外,如果 (function() { 'use strict'; angular.module('app.vendeurController', ["ngStorage"]). controller('vendeursController', function($scope, $http, $localStorage){ $scope.vendeur = {}; var vendeursList = []; $scope.saveData = function() { vendeursList = JSON.parse(localStorage.getItem('objVendeur')); var nVendeur = angular.copy($scope.vendeur); vendeursList.push(nVendeur); localStorage.setItem('objVendeur',JSON.stringify(vendeursList)); } }); })(); 为空,请检查您的逻辑,然后再推送它  例如:
//从localStorage解析后

vendeursList

答案 1 :(得分:0)

我试着理解为什么,但这段代码很好。

(function() {
'use strict';

angular.module('app.vendeurController', ["ngStorage"]).
controller('vendeursController', function($scope, $http, $localStorage){

    $scope.vendeur = {};
    $scope.objVendeur = [];

    $scope.saveData = function() {
        $localStorage.objVendeur.push(angular.copy($scope.vendeur));
    }

    $scope.objVendeur = $localStorage.objVendeur;

});
})();