正如您在Angularjs常见问题解答中所读到的那样,$rootScope
不鼓励使用.因此,服务更适合存储稍后将在控制器之间共享的数据.但是我无法在ng-show
不使用的情况下使指令工作$rootScope
.
这就是我正在做的事情;
的index.html
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
不绑定/更新此更改!
这只是一次评估的作业:
$scope.showSettings = globalService.getAll().showSettings;
所以价值永远不会改变.
至少有可能的解决方案:
将服务分配给范围:$ scope.settings = globalService.现在您可以在视图中访问该服务:
ng-show="settings.getAll().showSettings"
或者自己注册手表:
$scope.showSettings = false; $scope.$watch(globalService.getAll().showSettings, function(newValue){ $scope.showSettings = newValue; });