简体   繁体   中英

Complete http request before loading template

My template loads first then http request is fired because of which when I load page first time it shows 404 image src not found in console but then after micro-seconds loads data successfully. After googling a bit I found that we can handle this situation using resolve property.Below is my implementation of resolve.

var app=angular.module('websiteApp',['ui.router']);

app.config(function($stateProvider,$urlRouterProvider,$httpProvider){
$urlRouterProvider.otherwise("/movies");
$stateProvider.state('movies',
    {
        url:"/movies",
        templateUrl:"views/movies.html",
        controller:"moviesController",
        resolve:
        {
         movieslist:moviesController.getallMovies
        }
    })});

My Controller :

var moviesController=app.controller('moviesController',
function($scope,movieslist){
$scope.movies=movieslist.data.result
});

moviesController.getallMovies=function($q,$timeout,movieservice)
{
var defer=$q.defer();
$timeout(function(){
    defer.resolve(movieservice.getlist());
},1000);
return defer.promise;
}

My Service :

app.factory('movieservice',function($http,$location){
var movieserviceObj={};
movieserviceObj.getlist=function(){
dataString={mode:'list',page:1,recordsperpage:10};
return $http({ url:'app/api/entertainment.php',data:$.param(dataString),method:'POST'});
};
return movieserviceObj;

});

My Template [Sample] :

<div class="col-sm-6 col-md-3" ng-repeat="movie in movies"> 
<img src='public/images/{{movie.image}}' style="width: 175px;"/> 
</div>

But still my movies.html loads before my http request(1 sec delay) so my console error is still not disappeared.Is this the correct way to implement resolve in angularjs.

From Angular documentation ( https://docs.angularjs.org/api/ng/directive/ngSrc ):

ngSrc - directive in module ng

Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.

The buggy way to write it:

<img src="http://www.gravatar.com/avatar/{{hash}}"/>

The correct way to write it:

<img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>

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