正如您可能在 Angularjs FAQ 上读到的那样使用$rootScope
不鼓励。因此,服务更适合存储稍后在 Controller 之间共享的数据。但我无法创建 ng-show
指令工作无需使用 $rootScope
。
这就是我正在做的事情;
index.html
<div ng-controller="GlobalCtrl">
<div ng-show="showSettings"></div>
<aside ng-show="showSettings" >
<h1>Some text</h1>
<button ng-click="closeSettings()">Ok</button>
</aside>
</div>
app.js (我引导应用程序,因为我正在为 Cordova 开发..代码被截断)
var app = angular.module('tibibt', ['tibibt.controllers', 'tibibt.filters', 'tibibt.services']);
angular.element(document).ready(function () {
angular.bootstrap(document, ['tibibt']);
});
services.js
/* Create an application module that holds all services */
var tibibtServicess = angular.module('tibibt.services', []);
/* Global service */
tibibtServicess.service('globalService', function () {
this.Data = {
showSettings: 'false'
};
this.getAll = function () {
return this.Data;
};
this.setSettings = function (val) {
this.Data.showSettings = val;
};
});
controllers.js
/* Create an application module that holds all controllers */
var tibibtControllers = angular.module('tibibt.controllers', []);
tibibtControllers.controller('GlobalCtrl', function ($scope, globalService) {
// Get initial value
$scope.showSettings = globalService.getAll().showSettings;
console.log('Settings initially set to -> ' + globalService.getAll().showSettings);
// Open settings menu
$scope.openSettings = function () {
globalService.setSettings('true');
console.log('Settings set to -> ' + globalService.getAll().showSettings);
};
// Close settings menu
$scope.closeSettings = function () {
globalService.setSettings('false');
console.log('Settings set to -> ' + globalService.getAll().showSettings);
};
});
控制台显示更改,但 ng-show
不绑定(bind)/更新此更改!
最佳答案
这只是一个评估一次的作业:
$scope.showSettings = globalService.getAll().showSettings;
所以这个值永远不会改变。
至少有可能的解决方案:
将服务分配给范围:$scope.settings = globalService。现在您可以访问您 View 中的服务:
ng-show="settings.getAll().showSettings"
或自行注册 watch :
$scope.showSettings = false; $scope.$watch(globalService.getAll().showSettings, function(newValue){ $scope.showSettings = newValue; });
关于angularjs - 如何在没有 $rootScope 的情况下切换 Angularjs ng-show,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20933502/