Skip to content Skip to sidebar Skip to footer

AngularJS Using Service Variable With Ng-if

I want to be able to determine which directive is displayed based on a variable from a shared service. This is what I have so far. main.html ).controller('MainController', MainController) MainController.$inject = ['stateChangeService']; function MainController(stateChangeService){ var vm = this; vm.stateChangeService = stateChangeService; } <body ng-controller="MainController as mc"> <character-select ng-if="mc.stateChangeService.playerState === 'characterSelect'"></character-select> <fight-display ng-if="mc.stateChangeService.playerState === 'fight'"></fight-display> </body>

Solution 2:

View in Angular can access variables in current $scope or parent scopes. so you have to assign service to current $scope or $rootScope.

(function() {
  angular.module('app')
  
  // your service 
 .service('myService', myServiceFunction);
      function myServiceFunction(){
        this.data = function(){ return true;    };
      };
     


  // your controller
  .controller('myController', myControllerFunction);

  // inject $scope and service
  myControllerFunction.$inject=['$scope','myService'];

  function myControllerFunction($scope, myService){
    //attatch service to current scope
    $scope.myService = myService;  
  };
  
})();

 
<div ng-app='app' ng-controller="myController">
{{myService.data()}}
</div>

Solution 3:

You can only use those variable on view/HTML which are bounded to $scope or this(while using controllerAs pattern). You should expose your service/factory/constant on view, OR rather better way would write a getter for accessing particular variable from service. Its best practice to expose relevant matter from service. There after you could call that getter from view like getPlayerState()

HTML

<character-select ng-if="getPlayerState() === 'characterSelect'"></character-select>
<fight-display ng-if="getPlayerState() === 'fight'"></fight-display>

Code

app.controller('myCtrl', function(stateChangeService, $scope){

   $scope.getPlayerState = function(){
      return stateChangeService.playerState;
   }

})

Post a Comment for "AngularJS Using Service Variable With Ng-if"