AngularJS using service variable with ng-if

2019-09-14 15:55发布

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

<character-select ng-if="stateChangeService.playerState === 'characterSelect'"></character-select>
<fight-display ng-if="stateChangeService.playerState === 'fight'"></fight-display>

service

  angular
    .module('outerZone')
    .service('stateChangeService', stateChangeService);

  function stateChangeService() {
    var vm = this;

    vm.playerState = 'characterSelect';

  }

Currently when I load the page, nothing displays. The service is injected into both the character-select directive and the fight-display directive as well as the MainController. Any ideas?

3条回答
Juvenile、少年°
2楼-- · 2019-09-14 16:29

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>

查看更多
forever°为你锁心
3楼-- · 2019-09-14 16:35

There is no way your view knows anything about your service. You should assign your service to context.

angular.module('outerZone').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>
查看更多
混吃等死
4楼-- · 2019-09-14 16:51

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;
   }

})
查看更多
登录 后发表回答