2015-05-26 5 views
0

Я не могу добавить данные в массив. Посмотрел на все решения здесь, на сайте, попробовал push.apply, concat ... ничего не работает.Невозможно применить данные JSON к массиву - AngularJS

Вот мой код:

Контроллер:

myApp.controller('ordersController', function ($scope, customerFactory){ 
     $scope.products = []; 
     customerFactory.getCustomers(function (data){ 
      $scope.customers = data; 
     }) 
     $scope.addProduct = function(){ 
      for (var i = 0; i < $scope.customers.length; i++){ 
       if ($scope.newProduct.customer == $scope.customers[i].name){ 
        $scope.customers[i].push({product:$scope.newProduct.name, quantity:$scope.newProduct.quantity}); 
        $scope.newProduct = ''; 
       } 
      } 
     } 
    }); 

Обеспечение завода, а также:

myApp.factory('customerFactory', function(){ 
     // a factory is nothing more than a function that returns an object literal! 
     var customers = [ 
      {name:'John Lennon', created_date: 'April 3rd 2014'}, 
      {name:'Paul McCartney', created_date: 'April 3rd 2014'}, 
      {name:'George Harrisson', created_date: 'April 1st 2014'}, 
      {name:'Ringo Starr', created_date: 'March 15th 2014'}]; 
     var factory = {}; 
     // add a getstudents method to the object we defined 
     factory.getCustomers = function (callback){ 
      // pass the students to a callback to be used by whoever calls the method 
      callback(customers); 
     } 
     // most important step: return the object so it can be used by the rest of our angular code 
     return factory; 
    }); 

Я получаю ошибку:

"Error: $scope.customers[i].push is not a function [email protected]:///C:/Users/Salamat/Documents/MEAN/AngularJS/static/test.html#/orders:53:1 
[email protected]://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js:12404:15 
ngEventHandler/</[email protected]://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js:21566:17 
$RootScopeProvider/this.$get</[email protected]://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js:14466:16 
$RootScopeProvider/this.$get</[email protected]://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js:14565:18 
ngEventHandler/<@https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js:21571:17 
createEventHandler/[email protected]://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js:3032:9 
" 
+0

Какую ошибку вы получаете в консоли браузера? Вы можете поделиться им? Ах, я вижу ошибку с консоли. – immirza

+0

Это в нижней части моего сообщения. –

+0

Пожалуйста, объявите $ scope.customers массива типов. Push работает только для типов массивов. http://www.w3schools.com/jsref/jsref_push.asp – immirza

ответ

2

вы не можете использовать толчок За все. Push работают только для массива

Подобно этому

var customers = [ 
      {name:'John Lennon', created_date: 'April 3rd 2014'}, 
      {name:'Paul McCartney', created_date: 'April 3rd 2014'}, 
      {name:'George Harrisson', created_date: 'April 1st 2014'}, 
      {name:'Ringo Starr', created_date: 'March 15th 2014'}]; 

customers.push({name:'dummy',created_date: 'April 3rd 2014'}); 

Если вы хотите, чтобы добавить еще один объект внутри собственности клиента, как продукт, который вы должны объявить, что как массив

var customer=[{name:'John Lennon', created_date: 'April 3rd 2014',product:[]}]; 
customer[0].product.push({}); 

или попробовать, как это

var customers = [ 
       {name:'John Lennon', created_date: 'April 3rd 2014'}, 
       {name:'Paul McCartney', created_date: 'April 3rd 2014'}, 
       {name:'George Harrisson', created_date: 'April 1st 2014'}, 
       {name:'Ringo Starr', created_date: 'March 15th 2014'}]; 
customers[0].product=[]; 
customers[0].product.push({}); 
+0

Это помогло. Спасибо! –

+0

Добро пожаловать :) –

0

Все это похоже на эффект «обратного вызова». Вы можете вернуть клиентов из заводских функций getCustomers. Как показано ниже:

myApp.factory('customerFactory', function(){ 
     // a factory is nothing more than a function that returns an object literal! 
     var customers = [ 
      {name:'John Lennon', created_date: 'April 3rd 2014'}, 
      {name:'Paul McCartney', created_date: 'April 3rd 2014'}, 
      {name:'George Harrisson', created_date: 'April 1st 2014'}, 
      {name:'Ringo Starr', created_date: 'March 15th 2014'}]; 
     var factory = {}; 
     // new getCustomers function which does not accept a callback as param. 
     factory.getCustomers = function(){ 
      return customers; 
     } 
     // most important step: return the object so it can be used by the rest of our angular code 
     return factory; 
    }); 

А в магазине контроллера, она, как

$scope.customers = customerFactory.getCustomers(); 
0

Я предполагаю, что вы хотите, широкий спектр продуктов на одного клиента, так что вам нужно products свойство, чтобы добавить newProduct к.

$scope.addProduct = function() { 
    for (var i = 0; i < $scope.customers.length; i++) { 
    if ($scope.newProduct.customer == $scope.customers[i].name) { 
     var cust = $scope.customers[i]; 
     if (typeof cust.products === 'undefined') { 
     // Add the products array if it isn't already there 
     cust.products = []; 
     } 
     // Then add the new product 
     cust.products.push({ 
     product: $scope.newProduct.name, 
     quantity: $scope.newProduct.quantity 
     }); 
     $scope.newProduct = ''; 
    } 
    } 
} 
Смежные вопросы