使ng-show/ng-hide与由Angular之外的外部源修改的localStorage一起工作

Making ng-show/ng-hide work with localStorage being modified by external sources outside of Angular?

本文关键字:外部 修改 localStorage 工作 一起 ng-show ng-hide 与由 Angular      更新时间:2023-11-25

这是我的登录覆盖的顶级控制器。

login.controller('main_controller', ['$scope', function ($scope) {
    $scope.shouldShowLoginOverlay = function () {
        return (null == localStorage.getItem("auth_token"));
    }
}]);

这是相应的HTML。

<div ng-controller = "main_controller" ng-show="shouldShowLoginOverlay()"></div>

登录后,我在localstorage中设置auth_token,覆盖就会自动消失。我尝试使用removeItem删除chrome资源部分的条目,甚至删除JS控制台。在这种情况下,覆盖不会自动出现!我是刚接触棱角分明的人,我缺少什么?

您可以尝试类似的东西

view.html
<p align="center" ng-show="yourFunction() == true">will show when you had something valued as True on local storage</p>

controller.js
$scope.yourFunction = function() {
  return localStorage.getItem("your_local_storage")
}

试试这个

<div ng-controller = "main_controller" ng-show="isAuthenticated" ng-init="shouldShowLoginOverlay()"></div>

并将控制器更改为:-

login.controller('main_controller', ['$scope', function ($scope) {
    $scope.shouldShowLoginOverlay = function () {
      $scope.isAuthenticated  = (null == localStorage.getItem("auth_token"));
      return $scope.isAuthenticated;
    }
}]);

此外,我建议使用服务或工厂来实现登录身份验证模块。

可以通过向覆盖中添加类来尝试不同的问题解决方案。类似于,.show { display: block; } .hide { display: none; }我有一把小提琴给你。

请尝试以下伪代码

<body ng-controller="test">
    <div ng-show="istrue">fadf</div>
    <input type="button" ng-click="addItem()" value="add" />
    <input type="button" ng-click="removeItem()" value="Remove" />
    <script>
        var myApp = angular.module("MyApp", ["ngAnimate"]);
        myApp.controller('test', function ($scope) {
            alert(localStorage.getItem("auth_token"));
            $scope.$watch(function () {
                return (null != localStorage.getItem("auth_token"));
            }, function (newvalue, oldvalue) {
                $scope.istrue=newvalue
            });
            $scope.addItem = function () {
                var testObject = { 'one': 1, 'two': 2, 'three': 3 };
                localStorage.setItem('auth_token', JSON.stringify(testObject));
            }
            $scope.removeItem = function () {
                localStorage.removeItem('auth_token');
            }
        });

    </script>
</body>