AngularJS使用服务变量和ng-if

时间:2016-09-10 21:33:43

标签: javascript angularjs service controller

我希望能够根据共享服务中的变量确定显示哪个指令。这是我到目前为止所做的。

main.html中

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

服务

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

  function stateChangeService() {
    var vm = this;

    vm.playerState = 'characterSelect';

  }

目前,当我加载页面时,没有任何内容显示。该服务被注入到character-select指令和fight-display指令以及MainController中。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

您的观点无法了解您的服务。您应该将服务分配给上下文。

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>

答案 1 :(得分:0)

您只能在视图/ HTML上使用那些与$scopethis绑定的变量(使用controllerAs模式时)。您应该在视图上公开service/factory/constant,或者更好的方法是编写一个用于从服务访问特定变量的getter。从服务中揭示相关问题的最佳做法。在你可以从getPlayerState()

这样的视图中调用该getter之后

<强> HTML

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

<强>代码

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

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

})

答案 2 :(得分:0)

Angular中的视图可以访问当前$ scope或parent范围中的变量。 所以你必须将服务分配给当前的$ scope或$ rootScope。

&#13;
&#13;
(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;  
  };
  
})();

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