0

If I have a standard factory, creating a person, say:

      $scope.person = Person.get({person: $routeParams.person},function () {
  },function (httpResponse) {
  });

My HTML is:

<div>Person is: {{person}}</div>

Fairly straightforward. My issue is with rendering. My understanding is that when this runs, it immediately returns an empty object; when the async get finally returns, it will fill in $scope.person, and then re-render.

  1. What prevents this from just rendering as Person is: and then rerendering as Person is: John? I don't want that blank, if anything, I want to show some "loading" and then change it when render is complete.
  2. How do I handle errors? If I get a 404 - say the person ID is non-existent - I want to show some form of "sorry, the user you requested doesn't exist". But I want to be sure that shows only after I actually tried, not accidentally render it while waiting for the person to load.
4

2 回答 2

3

我们是如何处理的:

  • 实施了一个busy指令。在您的情况下,它将被应用为:

    <div busy="!person.$resolved">Person is: {{person.name}}</div>
    

    (另请注意,我稍微改变了人,成为一个对象)

  • busy 指令的实现或多或少是(我们使用的是 jQuery):

    app.directive("busy", function() {
        return {
            restrict: "A",
            link: function(scope,element,attrs) {
                var wrapper = element.wrap("<div class="busy-wrapper"></div>");
                scope.$watch(attrs.busy, function(busy) {
                    if( busy ) wrapper.addClass("busy");
                    else wrapper.removeClass("busy");
                });
            }
        });
    });
    
  • 然后是 CSS:

    .busy-wrapper.busy * {
        display: none; /* we hide the content when busy */
    }
    .busy-wrapper.busy {
        /* display a spinner */
        background: white url("my-busy-spinner.gif") no-repeat center;
        height: 50px; /* Depends... */
    }
    
  • 当我们发现一个错误时,我们用一个$error=true属性标记资源对象(这里是人):

    $scope.person = Person.get(...,
        function() { /* success */ },
        function(response) {
            $scope.person.$error = true; // and maybe more stuff from the response, e.g. a $message attribute
        }
    );
    

    我们如何处理$error属性取决于上下文;有时我们隐藏输出并显示“重试”链接,例如:

    <div ng-if="!person.$error" busy="!person.$resolved">Person is: {{person.name}}</div>
    <div ng-if="person.$error">Something bad happened. <a ng-click="retry()">Retry!</a></div>
    

不是确切的代码,但我认为它为您提供了一个总体思路。此外,这不是唯一正确的方法(我对其他人感兴趣),只是我们的做法。哦,你可以在忙碌时做各种好事,比如添加动画/过渡。

于 2013-09-28T19:22:58.963 回答
1

您可以使用ngCloak

来自 AngularJS

ngCloak 指令用于防止 Angular html 模板在加载应用程序时被浏览器以原始(未编译)形式短暂显示。使用该指令可以避免 html 模板显示引起的不良闪烁效果。

于 2013-09-28T18:39:54.223 回答