正如您可能已閱讀Angularjs FAQ,不鼓勵使用$rootScope
。因此,一項服務更適合於存儲稍後將在控制器之間共享的數據。但是,如果不使用$rootScope
,我不能使ng-show
指令正常工作。
這是我正在做的事情;
的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 (我自舉程序因爲我開發科爾多瓦..代碼截斷)
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
並不/更新綁定到這個變化!
NG-顯示字符串轉換爲默認布爾值。 – numediaweb
哦,我看到你更新了答案..將檢查它:) – numediaweb
@numediaweb:它應該是'$ scope.Data = globalService.getAll();'。我再次更新了我的答案。輸入太快就犯了一個錯誤。 –