如何让 AngularJS 有条件地不执行 div 中的任何代码



多亏了这个问题的答案,我能够制作一个从 AJAX 调用中获取数据的 DIV,如果它从后端收到错误 401,它将优雅地显示一条很好的消息。

但是,我注意到当它收到 401 错误时,即使它隐藏了显示它将收到的数据的div,我仍然在 Firebug 中看到它正在尝试显示此数据。

我怎样才能告诉 AngularJS 不仅隐藏这个区域,而且根本不在其中执行任何内容?

<div class="pageContent">
    <h2>Showcase AngularJS 4</h2>
    <div ng-app="mainApp">
        <div ng-controller="projectManagerController">
            <div class="projectManagerArea">
                <div class="hasAccess" ng-show="projectManagers != '[noAccess]'">
                    <h3>Project Managers</h3>
                    <ul ng-repeat="projectManager in projectManagers | orderBy: 'surname'">
                        <li>{{projectManager.surname}}</li>
                    </ul>
                </div>
                <div class="hasNoAccess" ng-show="projectManagers == '[noAccess]'">
                    (no access to project managers)
                </div>
            </div>
        </div>
    </div>
    <script>
        var app = angular.module('mainApp', []);
        app.controller('projectManagerController', function ($scope, $http) {
            $scope.message = 'Here are the project managers:';
            $http.get("<?= qsys::getFullUrl("task/showcaseAngularjs3") ?>")
                    .success(function (response) {
                        $scope.projectManagers = response;
                    })
                    .error(function (error) {
                        $scope.projectManagers = '[noAccess]';
                    });
        });
    </script>
    <style type="text/css" scoped>
        .projectManagerArea {
            border: 1px solid #ddd;
            background-color: #eee;
            width: 500px;
            padding: 10px;
            border-radius: 5px;
        }
        .projectManagerArea h3 {
            font-size: 14px;
            margin: 0;
            border-bottom: 1px solid #ccc;
        }
    </style>
</div>

使用 ng-if 而不是 ng-show。Ng-show 仅使用 CSS 来隐藏 DOM 元素,但仍然尝试创建它,而 ng-if 会在 'projectManagers!= '[noAccess]'' 时重新创建div,并在不满足条件时将其删除。

<div class="hasAccess" ng-if="projectManagers != '[noAccess]'">

相关内容

最新更新