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']; functionMainController(stateChangeService){ var vm = this; vm.stateChangeService = stateChangeService; } <body ng-controller="MainController as mc"> <character-selectng-if="mc.stateChangeService.playerState === 'characterSelect'"></character-select><fight-displayng-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);
      functionmyServiceFunction(){
        this.data = function(){ returntrue;    };
      };
     


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

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

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

 
<divng-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-selectng-if="getPlayerState() === 'characterSelect'"></character-select><fight-displayng-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"