我希望能够根据共享服务中的变量确定显示哪个指令。这是我到目前为止所做的。
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中。有什么想法吗?
答案 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上使用那些与$scope
或this
绑定的变量(使用controllerAs模式时)。您应该在视图上公开service/factory/constant
,或者更好的方法是编写一个用于从服务访问特定变量的getter。从服务中揭示相关问题的最佳做法。在你可以从getPlayerState()
<强> 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。
(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;