0
<!-- featured items table -->
<ul>
<li ng-repeat="item in items track by item.id">
<a href="" ng-click="addCart(item.id)">{{item.status}}</a>
</li>
</ul>

<!-- another tabs from same data table -->
<ul>
<li ng-repeat="item in items track by item.id">
<a href="" ng-click="addCart(item.id)">{{item.status}}</a>
</li>
</ul>

<script>
// controler
//items array here
// controller end

// start add to cart controller
$scope.addCart = function(id){
$scope.items[id].status = 'added';
}
//end of add to cart controller
</script>

i am new in angular js my code is look like as i wrote above i want to make a function addtocart just once and when i click this function i want replace the whole page row where item.id match whataever if id else where inside ng-repeat whatever if id match both ng-repeat. when i try to do that i got error about access array and sometime work only for 1 row. any idea suggestion what i need to do ? thankyou

regards, Ahsan Haroon

2 Answers2

1

The service() function will instantiate the instance using the new keyword when creating the instance.

 var Person = function() {
                var items = [{id:1,title:'test1'},{id:2,title:'test2'}];
                module.service('MyService', function() {
               this.getItems = function() {
                 return items; //.. get your item array
                }

               this.setItems = function() {
               // Update your item array and return it.
               return items;
               }
            });
      };

   angular.service('personService', Person);
Jigar7521
  • 1,549
  • 14
  • 27
  • do i need to change my items array function ? i mean should i put my `items` array function inside of `person function`? or it will get my `items` array from my controller ? –  Nov 21 '16 at 08:52
  • Yes of course, this was what i talking about, you need to just put initially your array @var items and then you can get it or set it when and where you required it in any controller by just injecting dependency. – Jigar7521 Nov 21 '16 at 09:00
0

You need to do something like this..

var app = angular.module('example', []);

app.service('arrayService', function() {
  return function() {
      this.getArray = function() {
      return [1, 2, 3, 4, 5];
    }
}
})
app.factory('arrayFactory', function() {
     return {
          getArray : function() {
          return [9,8,7,6,5];
     }
}
})
app.controller('MainCtrl', ['$scope','arrayService','arrayFactory',
     function($scope, arrayService,arrayFactory) {
     var ary = new arrayService();
     $scope.serviceArrayObject = ary.getArray();
     $scope.factoryArrayObject = arrayFactory.getArray()
     }
]);

But be careful, once you refresh the browser, arrays will be re-initialized. Use cookies or local storage to maintain the state of the arrays.

Akash Agrawal
  • 2,219
  • 1
  • 17
  • 38