Search code examples
angularjsangular-factory

ng-click function in angularjs factory


I would like to change a variable in a angularjs (1.x) factory with a click event. After that the pause button should appear. Could you please help me:

The link with ng-click:

<li ng-click='navPlayMusic()'>
  <a class="glyphicon glyphicon-play music-control"></a>
</li>
<li ng-show="musicControl.playTitle === true" ng-click='navPauseMusic()'>
  <a class="glyphicon glyphicon-pause music-control"></a>
</li>

EDIT:

The controller:

music.controller('musicController', function($scope, $rootScope, $location, musicControl) {
  ...
  $scope.musicControl = musicControl;
  $scope.navPlayMusic = function() {
     musicControl.playMusic();
  }
  ...
});

The factory:

music.factory('musicControl', function () {
return {
  playTitle: false,
};
this.playMusic = function() {
  return {
    playTitle: true
  };
 };
});

Solution

  • You can try this

    Factory:

        music.factory('musicControl', function() {
            var _flags = {  //Note: we intentionally declare properties here for easy to track how many flag we have in factory (optional)
                playTitle: false 
            }
            return {
                flags: _flags,
                playMusic: playMusic
            };
    
            function playMusic(dummyParam) {
                //handle play music logic
                //dummyParam will be 5 if called from HTML.
    
                //after done, enable the flag
                _flags.playTitle = true;
            };
        });
    

    Controller:

        music.controller('musicController', function($scope, $rootScope, $location, musicControl) {
    
            //...
    
            $scope.musicFlags = musicControl.flags;   //map only property that we need to use. More than that is just make code hard to understand
            $scope.navPlayMusic = musicControl.playMusic; //just need to map function
    
            //...
    
        });
    

    HTML:

        <li ng-click='navPlayMusic()'>
            <a class="glyphicon glyphicon-play music-control"></a>
        </li>
        <li ng-show="musicFlags.playTitle === true" ng-click='navPauseMusic(5)'>
            <a class="glyphicon glyphicon-pause music-control"></a>
        </li>