AngularJS使用服务变量ng-if [英] AngularJS using service variable with ng-if

查看:259
本文介绍了AngularJS使用服务变量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

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

  }

目前加载页面时,不显示任何内容。该服务被注入到字符选择指令和战斗显示指令以及MainController。任何想法?

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?

推荐答案

您只能在视图/ HTML上使用这些变量,其范围为 $ scope (使用controllerAs模式时)。你应该公开你的服务/工厂/常数在视图,或者更好的方式将写一个getter从服务访问特定的变量。其最佳做法是使相关物质免受服务。之后,您可以从 getPlayerState()

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 / p>

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

})

这篇关于AngularJS使用服务变量ng-if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆