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

标签 angularjs angularjs-scope

正如您可能在 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;

所以这个值永远不会改变。

至少有可能的解决方案:

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

    ng-show="settings.getAll().showSettings"
    
  2. 或自行注册 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/

相关文章:

javascript - Angular $q 然后 hell

javascript - 在 Ionic 中处理 CORS 问题

javascript - Ionic fab 按钮在 App 中显示不正确

javascript - 一款 watch 功能内含两种型号

angularjs:当我使用 jQuery 更改选择时 $scope 更新

javascript - 具有动态选择字段的表单无法验证

mysql - 哪个更好 : single or multiple database connections?

javascript - nwdirectory 作为模型传递给 Angular

angularjs - 没有模板的 Angular 组件表达式绑定(bind)

javascript - 范围未在 http.get 的成功函数内更新 UI