diegoaguilar
diegoaguilar

Reputation: 8376

How should I use Angular services with factories for code reuse?

I have some Angular Controllers where there's always the need to store an array of items, push elements to it and make it accessible.

I thought then I could have a ServicesModule with a factory offering such service.

So I got this service declaration:

angular.module('ServicesModule',[]);

    angular.module('ServicesModule')
        .factory('newOrdersService', function($rootScope,$http) {

            var newOrder = [];
            return {
                getOrder: function() {return newOrder;},
                addItem:    function(item) {newOrder.push(item);}
            };
        });

I got this controller example where I use the service:

angular.module('app',['ServicesModule']);


angular.module('app').
  controller('MainController', function($scope, $http, newOrdersService){

      $scope.order = newOrdersService.getOrder();
      $scope.addItem = newOrdersService.addItem();
  });

However I can't get it working, seems like using either getOrder or addItem from the service won't make any effect.

What am I doing wrong?

I offer a plunkr example:

Upvotes: 0

Views: 217

Answers (1)

Kjell Ivar
Kjell Ivar

Reputation: 1164

I forked your plunker.

You can bind your scope variables directly to a function.

$scope.addItem = newOrdersService.addItem;

Alternately:

$scope.addItem = function(item){
    newOrdersService.addItem(item);
}

$scope.addItem = newOrdersService.addItem() doesn't work as this will only run your addItem once when the controller is loaded.

And when you add a new item, it's important that you create a new object, or else the objects inside your array will continue being bound to the ng-models (and changed when you enter something into the text inputs).

Upvotes: 1

Related Questions