如何在AngularJs中实际使用ng-Cloak指令?

How to use the actual use of ng-Cloak directive in AngularJs?

  1. 什么是 ng-cloak 指令?
  2. 我们为什么要使用它?

ng-斗篷

来自文档:

The ngCloak directive is used to prevent the Angular 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.

简而言之,您可以使用ng-cloak指令来防止显示未编译的元素。未编译元素可以是保存并等待传入​​数据的元素:

<div ng-cloak>{{myvar}}</div>

如果 myvar 控制器仍未编译或数据未填充 ng-cloak 阻止显示 {{myvar}} 并且仅在编译变量时显示 div .

按照此代码示例并检查 results 有无 ng-cloak:

<style>
    [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-    ng-cloak {
        display: none !important;
    }
</style>

<body ng-controller="MyController" ng-cloak>
    <h3>ngCloak Example</h3>
        <ol >
            <li ng-repeat="item in myData">
                {{item.title}}
            </li>
        </ol>
</body>


var myApp= angular.module("myApp",['ngResource']);

myApp.controller("MyController", ["$scope", "$resource","$timeout",
    function($scope,$resource,$timeout){
        $scope.myData =[];

        var youtubeVideoService = $resource("https://gdata.youtube.com/feeds/api/videos?q=googledevelopers&max-results=5&v=2&alt=jsonc&orderby=published");

        youtubeVideoService.get()
            .$promise.then(function(responseData) {
        
        angular.forEach(responseData.data.items,
            function(aSingleRow){
                console.log(aSingleRow);
                $scope.myData.push({
                    "title":aSingleRow.title
                }); 
            });
        }); 
}]);    

Ben 给出的使用 ng-cloak 的理由是有效的,但是 Ben 提供的示例的结果在某些情况下仍然会显示 {{var}}。当脚本通常异步加载或放置在任何 html 正文的底部时,这在野外尤其如此。

在 Ben 的示例中,他在顶部放置了一个 <style> 但没有使用它,我们应该将 ng-cloak class 放置在 <body> 上,就像这样,并且使用该样式:

<body class="ng-cloak" ng-controller="MyController" ng-cloak> ...

这样,在 Angular 将 ng-cloak 更改为 display: block 或指令更新标记 html.

之前,不会显示 body 标签的内容

添加class的原因是因为在显示html之后解析了ng-cloak指令,所以总是您的 JS 线程死掉后仍然显示类似 {{something here}}.

的可能性

正确使用的一个很好的例子是在 ng-repeat 指令中包含 class="ng-cloak"ng-cloak 指令。

但是,如果只有 {{}} 很烦人,否则即使 JS 线程崩溃页面也很好,最好在您的标签上使用 ng-bind 而不是添加 {{}}在他们里面。

我想补充一点—— 我已经看到大多数应用程序,仅添加 ng-cloak 是行不通的。这是因为该页面可能更大,并且直到那时才加载 js。

为此指令手动应用 CSS 会有所帮助 -

[ng-cloak]  
{  
display: none !important;
}

希望这对某人有所帮助!