1

I want to pass a variable between controllers with a service. Here is the service to pass the variable (in this case a song id):

'use strict';

angular.module('PortalApp')
  .service('ActionbarService', ['$window', function ActionbarService(window) {
    var song;
    return {
        getSong: function () {
            return song;
        },
        setSong: function(value) {
            song = value;
        }
    };
  }]);

Here is the relevant part of the controller I am setting the song from:

$scope.actionbarSetSong = function(song_id) {
  ActionbarService.setSong(song_id);
}

and here is the controller I am getting the song id from:

'use strict';

angular.module('PortalApp')
  .controller('ActionbarCtrl', function ($scope, MediaService, ActionbarService, $location, $routeParams, AudioPlayerAPI) {
    $scope.song_id = ActionbarService.getSong();
    $scope.openPlaylistModal = function (song_id) {

      $("#addToPlaylist").modal('show');
    }
  });

It is being set in the service because when I do getSong in my view it worked (I forget where), but then when I try to set it in my 2nd controller it doesn't work. Here's the relevant part of my view for reference:

    <div class="cell action-bar" ng-click="actionbarSetSong(song.id);" ng-repeat="song in media.data">
Some Stuff
    </div>
6
  • 1
    Can't you just set the value in $rootScope? Then you wouldn't need the service. Commented Sep 18, 2013 at 19:04
  • Make sure both controllers are on the same page. Commented Sep 18, 2013 at 19:07
  • 1
    where is your player? data-ng-click="player.setSong(song.id);" Commented Sep 18, 2013 at 19:08
  • Sorry, that was another similarly-named thing. To be honest, I forget where we got player from. Commented Sep 18, 2013 at 19:35
  • Both controllers are on the same "page," but I'm not sure they're in the same scope. I think either one is a child of the other or both are the children of another scope. Sometimes it's hard to tell with Angular. Commented Sep 18, 2013 at 19:36

1 Answer 1

3

Mmm.. service returns new ActionbarService. You probably want to use factory, or change your getters/setters to this.get & this.set.

Also, avoid polluting the $rootScope; whenever you want to share data between controllers, use a service.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, there was another Stack answer on that (well, at least one), but it doesn't seem like good coding practice. I will look into using factories.
Sorry, I meant using $rootScope doesn't seem like good coding practice. Angular services seem fine, although strange and magical, like everything Angular.
Give it some time, it gets better :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.