Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to have an array in the service, which can be modified from different controllers. The purpose of this is the have an array accessible through every controller. I want to be able to push items to this array from controllers, as well to delete them.

Service:

.service('EmailOps', function () {

        var templates = [];

        return {

        pushToEmailBody: function (newObj) {

            templates.push(newObj);
            console.log(templates);

            }

        };
    });

Controller:

angular.module('app')
  .controller('mainCtrl', function ($scope, $rootScope, EmailOps) {

    $scope.include = EmailOps.pushToEmailBody;

});

HTML:

<div ng-controller="mainCtrl">

<a href="#" ng-click="include('one')">1</a>

<a href="#" ng-click="include('two')">2</a>

<a href="#" ng-click="include('three')">3</a>

</div>

To summarize, I would like to be able to add multiple new elements to the array in the service by clicking on these links. Currently when it adds one of them, it replaces the one added before, so that I have an array with one element only. Any idea what I might be doing wrong?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

please see here : http://jsbin.com/gesirira/1/edit

service:

   app.service('EmailOps', function () {

        var templates = [];


       function pushToEmailBody (newObj) {

                templates.push(newObj);
                console.log(templates);

                }

      return {

        templates:templates,
        pushToEmailBody : pushToEmailBody 

      };


     });

controller:

app.controller('firstCtrl', function($scope,EmailOps){

 $scope.include = function(obj)
 {
   EmailOps.pushToEmailBody(obj);
 };

  $scope.temp = EmailOps.templates;

});

html:

<body ng-app="app">
  <div ng-controller="firstCtrl">

  <a href="#" ng-click="include('one')">1</a>

 <a href="#" ng-click="include('two')">2</a>

 <a href="#" ng-click="include('three')">3</a>
    <br/>
    templates: {{temp |json}}
</div>
      </div>
</body>
share|improve this answer
    
Thanks, works great :) –  Leszek Kasperczyk Aug 8 at 12:06

You can modify your service like this

.service('EmailOps', function () {

    this.templates = [];

    this.pushToEmailBody = function (newObj) {

        templates.push(newObj);
        console.log(templates);

     }
});

and then in the controller :

$scope.include = function(obj)
 {
   EmailOps.pushToEmailBody(obj);
 };
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.