简体   繁体   中英

Rendering of template before a response from API in AngularJs

I am using angular-slick library to display items on a slide via ng-repeat . The items do I get with an asynchronous call to a API. The problem I have is that the template is rendered before a response from the API.

This is my controller

    angular.module('myApp')
  .controller('homepageCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) {
    $http({method: 'GET', url: 'https://myapi.com/xxxxxx'}).
    success(function(data, status, headers, config) {
            $scope.articlesSlide = data.articles
    });
  }]); 

This is my template

<slick infinite="true" dots="true" arrows="true">
          <div ng-repeat="articleSlide in articlesSlide">

          <a href="/{{articleSlide.cat}}/articulo/{{articleSlide.slug}}" class="dentro" title="Ver noticia">
            <div class="imagen"><img ng-src="{{articleSlide.image}}" alt="{{articleSlide.title}}" /></div>
            <div class="texto">
              <div class="inner">
                <div class="cat">{{articleSlide.0.cat}}</div>
                <h2>{{articleSlide.title}}</h2>
              </div>
            </div>
          </a>

          </div>
          </slick>

You need to make use of promise in order to wait for the http call to fetch the response from the server. After the promise is resolved then only it should populate the articlesSlide scope variable. In the template have a ng-show check on the articlesSlide variable so that when it is null then nothing is displayed (till the time promise is resolved)

DOCUMENTATION:

Angular Promise

Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM