延迟AngularJS中的模板渲染

时间:2015-08-10 10:04:29

标签: angularjs angular-promise angularjs-templates

背景信息

我是AngularJS的新用户,正在开发一款能够显示照片Feed的简单应用。我有2个观点:

  • 列表 - 显示所有照片列表的主视图
  • 明细 - 当您点击其中一张重定向的照片以查看该照片的详细信息时

我正在使用JSONP请求从远程URL获取照片供稿。为了避免在更改视图时多次获取它,我创建了一个提供者" feedFactory"附加到两个视图的控制器用于将提要对象提供到范围中。

我遇到的问题是我看到JavaScript错误(帖子底部显示错误),因为在最初渲染视图时未定义的值会传递给过滤器。这是因为视图立即呈现 - 在完成承诺并获取提要之前 - 然后值仍未定义。毕竟一切都正常显示,但我当然需要在JavaScript控制台中摆脱这些错误。

问题

如何推迟在模板中呈现视图,直到完成承诺并将Feed插入范围。

CODE

providers.js

var module = angular.module("flickrFeedProviders", []);

/* Factory providing a function that returns a promise object. Promise provides
   a feed after it is fetched. */
module.factory("feedFactory", ["$http", "$q",
    function($http, $q) {
        /* Adds unique "id" key to every object in the array */
        function indexList(photos) {
            for (var i = 0; i < photos.length; i++) {
                photos[i].id = i;
            }
        };

        /* URL from which the feed is fetched */
        var FEED_URL = "https://api.flickr.com/services/feeds/photos_public.gne?tags=potato&tagmode=all&format=json&jsoncallback=JSON_CALLBACK";

        /* Create a deffered object */
        var deferred = $q.defer();

        $http.jsonp(FEED_URL)
            .success(function(response) {
                indexList(response.items);
                /* Pass data on success */
                deferred.resolve(response)
            })
            .error(function(response) {
                /* Send friendly error message on failure */
                deferred.reject("Error occured while fetching feed");
            });

        /* Return promise object */
        return deferred.promise;
    }]);

controllers.js

var module = angular.module("flickrFeedControllers", [
    "flickrFeedProviders"
]);


/* Loads the whole feed - list of photos */
module.controller("photoListController", ["feedFactory", "$scope",
    function(feedFactory, $scope) {
        feedFactory.then(function(feed) {
            $scope.feed = feed;
        });
    }]);


/* Load only 1 photo */
module.controller("photoDetailController",
                  ["feedFactory", "$scope", "$routeParams",
    function(feedFactory, $scope, $routeParams) {
        var photoID = parseInt($routeParams.photoID);

        feedFactory.then(function(feed) {
            $scope.photo = feed.items[photoID];
        });
    }]);

filters.js

var module = angular.module("flickrFeedFilters", []);


/* Given author_id from Flickr feed, return the URL to his page */
module.filter("flickrAuthorURL", function() {
    var FLICKR_URL = "https://www.flickr.com/";

    return function(author_id) {
        return FLICKR_URL + "photos/" + author_id;
    };
})


/* Given author field from Flickr feed, return hid nickname only */
module.filter("flickrAuthorName", function() {
    /* Regular expression for author field from feed, that groups the name
       part of the string, so that it can be later extracted */
    var nameExtractionRegExp = /.* \((.*)\)/;

    return function(author) {
        return author.match(nameExtractionRegExp)[1];
    }
})


/* Given date ISO string return day number with added suffix st/nd/rd/th */
module.filter("dayNumber", function () {
    return function(dateISO) {
        var suffix;
        var date       = new Date(dateISO);
        var dayOfMonth = date.getDate();

        switch(dayOfMonth % 10) {
        case 1:
            suffix = "st";
            break;
        case 2:
            suffix = "nd";
            break;
        case 3:
            suffix = "rd";
            break;
        default:
            suffix = "th";
            break;
        }

        return dayOfMonth + suffix;
    };
});


/* Splits string using delimiter and returns array of results strings.*/
module.filter("split", function() {
    return function(string, delimiter) {
        return string.split(delimiter);
    };
});

photo-detail.html模板

<!-- Title -->
<a href="{{ photo.link }}" title="Go to photo's details"
   class="title-container">
  <h2 class="title">{{ photo.title }}</h2>
</a>

<!-- Photo author -->
<a href="{{ photo.author_id | flickrAuthorURL }}"
   title="Go to author's page"
   class="author-link">{{ photo.author | flickrAuthorName }}</a>

<!-- Publication date information -->
<div class="publication-date">
  Published:
  {{ photo.published | dayNumber }}
  {{ photo.published | date : "MMM yyyy 'at' h:mm" }}
</div>

<!-- Photo image -->
<img alt="{{ photo.title }}" ng-src="{{ photo.media['m'] }}" class="photo" />

<!-- Description -->
<p class="description">{{ description }}</p>

<!-- Tag list -->
<ul class="tag-list">
  <li ng-repeat="tag in photo.tags | split : ' '" class="tag">
    <a href="#/tag/{{ tag }}" title="Filter photos by this tag">{{ tag }}</a>
  </li>
</ul>

<!-- Back button -->
<a href="#/photos" title="Go back" class="back" />

其中一个控制台错误

Error: author is undefined
@http://localhost:8000/app/js/filters.js:24:9
anonymous/fn@http://localhost:8000/app/bower_components/angular/angular.js line 13145 > Function:2:211
regularInterceptedExpression@http://localhost:8000/app/bower_components/angular/angular.js:14227:21
expressionInputWatch@http://localhost:8000/app/bower_components/angular/angular.js:14129:26
$RootScopeProvider/this.$get</Scope.prototype.$digest@http://localhost:8000/app/bower_components/angular/angular.js:15675:34
$RootScopeProvider/this.$get</Scope.prototype.$apply@http://localhost:8000/app/bower_components/angular/angular.js:15951:13
done@http://localhost:8000/app/bower_components/angular/angular.js:10364:36
completeRequest@http://localhost:8000/app/bower_components/angular/angular.js:10536:7
requestLoaded@http://localhost:8000/app/bower_components/angular/angular.js:10477:1

http://localhost:8000/app/bower_components/angular/angular.js
Line 12330

其他错误

Error: string is undefined
@http://localhost:8000/app/js/filters.js:59:9
anonymous/fn@http://localhost:8000/app/bower_components/angular/angular.js line 13145 > Function:2:208
regularInterceptedExpression@http://localhost:8000/app/bower_components/angular/angular.js:14227:21
$RootScopeProvider/this.$get</Scope.prototype.$digest@http://localhost:8000/app/bower_components/angular/angular.js:15675:34
$RootScopeProvider/this.$get</Scope.prototype.$apply@http://localhost:8000/app/bower_components/angular/angular.js:15951:13
done@http://localhost:8000/app/bower_components/angular/angular.js:10364:36
completeRequest@http://localhost:8000/app/bower_components/angular/angular.js:10536:7
requestLoaded@http://localhost:8000/app/bower_components/angular/angular.js:10477:1

http://localhost:8000/app/bower_components/angular/angular.js
Line 12330

1 个答案:

答案 0 :(得分:1)

好的,总结一下评论和随后的聊天,这就是答案:

&#34;作者的原因未定义&#34;错误

事实证明,提升它的是自定义过滤器(flickrAuthorName)。 从模板:

<a ...>{{ photo.author | flickrAuthorName }}</a>

加载模板时,尚未从服务器获取数据,photo.authorundefined,并传递给过滤器。过滤器应该更加健壮,以检查这种边缘情况,只需返回undefined本身。

&#34;如何推迟在模板中呈现视图,直到承诺完成并将Feed插入范围?&#34;

已经回答here

我们的想法是配置Angular的$route服务(通过$routeProvider)等待呈现模板,直到某个承诺得到解决,例如:直到从服务器获取的某些数据到达。

accepted answer

复制/粘贴
$routeProvider.when("path", {
    controller: ["$scope", "mydata", MyPathCtrl], // NOTE THE NAME: mydata
    templateUrl: "...",
    resolve: {
        mydata: ["$http", function($http) { // NOTE THE NAME: mydata
            // $http.get() returns a promise, so it is OK for this usage
            return $http.get(...your code...);
        }]
        // You can also use a service name instead of a function, see docs
    },
    ...
});

这个机制也在Angular的$routeProvider文档中描述(在when()函数route参数的描述下)。