我的模板首先加载,然后触发http请求,因为当我第一次加载页面时,它显示在控制台中找不到404图像src,但在几微秒后成功加载数据。经过一番谷歌搜索后,我发现我们可以使用resolve属性来处理这种情况。下面是我的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
}
})});
我的 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;
}
我的服务:
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;
});
我的模板[示例]:
<div class="col-sm-6 col-md-3" ng-repeat="movie in movies">
<img src='public/images/{{movie.image}}' style="width: 175px;"/>
</div>
但是我的 movie.html 仍然在我的 http 请求之前加载(1 秒延迟),所以我的控制台错误仍然没有消失。这是在 angularjs 中实现解析的正确方法吗?
最佳答案
来自 Angular 文档 (https://docs.angularjs.org/api/ng/directive/ngSrc):
ngSrc - ng 模块中的指令
在 src 属性中使用 {{hash}} 之类的 Angular 标记无法正常工作:浏览器将从带有文字文本 {{hash}} 的 URL 中获取,直到 Angular 替换 {{hash}} 内的表达式。 ngSrc 指令解决了这个问题。
错误的编写方式:
<img src="http://www.gravatar.com/avatar/{{hash}}"/>
正确的写法:
<img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
关于javascript - 加载模板之前完成http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28234692/