num*_*web 3 angularjs angularjs-scope
正如您在Angularjs常见问题解答中所读到的那样,$rootScope不鼓励使用.因此,服务更适合存储稍后将在控制器之间共享的数据.但是我无法在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>
Run Code Online (Sandbox Code Playgroud)
app.js (我正在开发应用程序,因为我正在开发cordova ..代码被截断)
var app = angular.module('tibibt', ['tibibt.controllers', 'tibibt.filters', 'tibibt.services']);
angular.element(document).ready(function () {
angular.bootstrap(document, ['tibibt']);
});
Run Code Online (Sandbox Code Playgroud)
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;
};
});
Run Code Online (Sandbox Code Playgroud)
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);
};
});
Run Code Online (Sandbox Code Playgroud)
控制台显示更改但ng-show不绑定/更新此更改!
这只是一次评估的作业:
$scope.showSettings = globalService.getAll().showSettings;
Run Code Online (Sandbox Code Playgroud)
所以价值永远不会改变.
至少有可能的解决方案:
将服务分配给范围:$ scope.settings = globalService.现在您可以在视图中访问该服务:
ng-show="settings.getAll().showSettings"
Run Code Online (Sandbox Code Playgroud)或者自己注册手表:
$scope.showSettings = false;
$scope.$watch(globalService.getAll().showSettings, function(newValue){
$scope.showSettings = newValue;
});
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
5045 次 |
| 最近记录: |