javascript - Why does Angularjs Service Return a Character Array instead of an Array of Objects? -
i using service(.factory) hold array of objects/items gets updated multiple controllers , data pulled down each controller. each time add new array of data, push onto array. however, when attempt load array within controller can display view, returning character array makes impossible use ng-repeat iterate on values.
// controllers.js angular.module('myapp.controllers', []) .controller('mainctrl', function($scope, mainservice) { $scope.mainitems = mainservice.all(); // why return char array? // count $scope.getcount = function(item){ return temporder.getcount(item); } // add item $scope.additem = function(item){ temporder.additem(item); return temporder.getcount(item); } }) .controller('secondaryctrl', function($scope, mainservice) { $scope.items = mainservice.all(); // why return char array? // count $scope.getcount = function(item){ return temporder.getcount(item); } // add item $scope.additem = function(item){ temporder.additem(item); return temporder.getcount(item); } });
this service
// services.js angular.module('myapp.services', []) .factory('mainservice', function() { orderitems = []; return { all: function() { return orderitems; // why return char array??? }, getcount: function(item){ var count = 0; (i = 0;i<orderitems.length;i++) { if (orderitems[i] === item ){ count++; } } return count; }, additem: function(item) { orderitems.push(item); } } });
i've updated above code, reasons getting module not found
while adding in code snippet here.
refer this fiddle solution, i'm not sure went wrong, maybe can html passing in item.name
or key or maybe haven't initialized $scope.item = {}
in controller
, that's why remains undefined , angular can't bind it. remember angular won't bind values undefined on controller bootstrap
Comments
Post a Comment