1

I have service which has two function setItems() and getItems(). I am using getItems() function to get items array, and also setItems() function to set Items array dynamically from controller.

.service('ItemService', ['$http', function ($http) {
   var items = [{'id': '1', 'item_id': '1', 'item_name': 'Tomato', 'type_name': 'Vegitables','nos':'0'}, {'id': '2', 'item_id': '2', 'item_name': 'onion', 'type_name': 'Vegitables','nos':'0'}];
   return {
        getItems: function () {
        return items;
        },
       setItems: function (value) {
       items = value;
       }
   };
  }]);

My controller function is as follows

 .controller('aLLITEMSCtrl', ['$scope', '$stateParams', '$location', 'ItemService', '$timeout', 
function ($scope, $stateParams, $location, ItemService, $timeout) {
    var data = {};
    $scope.data = data;
    $timeout(function () {                    
        $scope.items = ItemService.getItems(); 
    }, 0);
   $scope.set_item_nos = function (type, index) {
       angular.forEach($scope.data.item[index], function (value, key) {
       if (key == 'nos') {
            $scope.data.item[index].nos = parseInt(value) + 1;
       } 
       });
      ItemService.setItems($scope.data.item);
   }
   $scope.goCart = function () {
       $timeout(function () {
           $scope.items = ItemService.getItems();
       }, 0);
      $location.path('/yourcart');
  }
  }])

Here I am using getItems() to get the items array. and also I am incrementing nos from another function and then calling setItems() to set array items again. Everything work fine as expected,I can go to home and back to same controller then also the last assigned value of items array is same.

how can I set the items array initially by using a ajax request ? I need something like

.service('ItemService', ['$http', function ($http) {
    var url =  'http://localhost/app/item/get/item';        
    var items = $http.get(url).then(function (response)  
                return response.data;
                });                   
    return {
       getItems: function () {
       return items;
       },
      setItems: function (value) {
      items = value;
      }
    };
    }]);

I have tried this but if I set Items array initially via $http request each time when I call this controller Items array get initialize with response. but I want to set it only once when I came into controller. Then I can use setItems method to dynamically change this array.

I am a newbie to angularJS. Any Help will be appreciable

Nakul
  • 77
  • 9

0 Answers0