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

 莫小北 发布于 2023-02-06 14:34

正如您在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不绑定/更新此更改!

1 个回答
  • 这只是一次评估的作业:

    $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;
       });
      

    2023-02-06 14:36 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有