如何在没有$ rootScope的情况下切换Angularjs ng-show

时间:2014-01-05 12:23:38

标签: angularjs angularjs-scope

正如您在Angularjs FAQ上所读到的那样,不鼓励使用$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>

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未绑定/更新此更改!

2 个答案:

答案 0 :(得分:5)

这只是一次评估的作业:

$scope.showSettings = globalService.getAll().showSettings;

因此价值永远不会改变。

至少有可能的解决方案:

  1. 将服务分配给范围:$ scope.settings = globalService。现在,您可以在视图中访问该服务:

    ng-show="settings.getAll().showSettings"
    
  2. 或自行注册手表:

     $scope.showSettings = false;
     $scope.$watch(globalService.getAll().showSettings, function(newValue){
        $scope.showSettings = newValue;
     });
    

答案 1 :(得分:3)

尝试:

$scope.Data = globalService.getAll();

HTML:

<div ng-controller="GlobalCtrl">
    <div ng-show="Data.showSettings"></div>
    <aside  ng-show="Data.showSettings" >
        <h1>Some text</h1>
        <button ng-click="closeSettings()">Ok</button>
    </aside>
</div>

DEMO

<强>解释

此行$scope.showSettings = globalService.getAll().showSettings;按值分配数据 =&gt; showSettings的值被复制到$scope.showSettings =&gt;它们是2个独立的内存块。当您更改globalService.Data.showSettings时,$scope.showSettings未更新,因为它是另一块内存。

更改为$scope.Data = globalService.getAll();通过引用分配数据 =&gt;他们指向同一块记忆。

相关问题