AngularJS 代码元素在获得 API 响应之前显示在 HTML UI 中

AngularJS code elements are displayed in the HTML UI before getting the API response

我正在使用 Angularjs and HTML5. I have a page where some elements depends on Angularjs 变量。 例如在我的 HTML 代码中我有:

<div class="col-xs-12 col-sm-4 top-buffer">
    <div class="info-box">
        <div data-ng-bind-html="statusClass"></div>
        <div class="info-box-content">
            <span class="info-box-text">Status</span> <span
                class="info-box-number">{{statusName}}</span>
        </div>
        <!-- /.info-box-content -->
    </div>
    <!-- /.info-box -->
</div>

或 ng-show 整个 div

<div data-ng-show="isBusy" class="col-xs-12 col-sm-6 col-sm-offset-3">

<div data-ng-show="!isBusy" class="col-xs-12 col-sm-6 col-sm-offset-3">

所以Ione被隐藏,一个被显示。

statusNamestatusClass,与 isBusy 和所有其他变量一样,都是从 Angularjs http 调用中检索的,所以有那么一秒钟我的页面看起来不一样。 我怎样才能避免这种行为?我想是否有可能在页面加载之前加载这个变量,但是对于 data-ng-bind-html?

我认为使用 ng-cloak 可以解决您的问题。

The ngCloak directive is used to prevent the AngularJS html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.

https://docs.angularjs.org/api/ng/directive/ngCloak

所以你可以做的是在页面加载之前对要等待呈现的元素调用 ng-cloak 指令。

<div ng-show="isBusy" class="col-xs-12 col-sm-6 col-sm-offset-3" ng-cloak>

更新(根据给定 fiddle):


ng-show 根据提供的表达式显示或隐藏给定的 HTML 元素。

The ngShow directive shows or hides the given HTML element based on the expression provided to the ngShow attribute.

https://docs.angularjs.org/api/ng/directive/ngShow

您呈现两个按钮。两个按钮具有相同的表达式,除了一个按钮检查表达式是否为 true 而另一个按钮检查表达式是否为 false

<!-- True -->
<button ng-show="clickedStartButton" ng-cloak>{{text}}</button>

<!-- False -->
<button ng-show="!clickedStartButton" ng-cloak>{{text2}}</button>

ng-show="!clickedStartButton" 将始终 return false 开始,因为尚未为其分配任何值。所以这个 button 会一直渲染。当然,当您执行 $scope.clickedStartButton = true 时除外。但是后来

<button ng-show="clickedStartButton" ng-cloak>{{text}}</button>

将在没有 {{text}} 属性 的情况下呈现。

您可以通过以下操作来避免它。检查 {{text2}} 是否设置。如果没有,则 hide else show

<button ng-if="!clickedStartButton && text2" ng-cloak>{{text2}}</button> 

演示版

var app=angular.module('timerApp', []);
app.controller('timerController', ['$scope', '$interval', '$timeout', function ($scope, $interval, $timeout) {
  $timeout(function() {$scope.text="PROVA"; $scope.text2="PROVA2"; $scope.clickedStartButton=true; }, 2000);
   
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Will be rendered after 2 seconds

<div ng-app="timerApp" ng-controller="timerController">
    <button ng-if="clickedStartButton" ng-cloak>{{text}}</button>
    <button ng-if="!clickedStartButton && text2" ng-cloak>{{text2}}</button>
</div>