【发布时间】:2017-06-14 04:54:37
【问题描述】:
我正在尝试在模板中显示来自$http 请求的数据,该模板显示在ng-view 中。
我做了一些测试,当数据不是来自解析 (ngRoute) 时,ngRepeat 工作正常(例如,如果我在 $scope.products 中硬编码对象数组)。我搜索了很多,找到了很多例子,但没有一个与这个特定问题有关。
代码如下:
app.js
"use strict";
angular.module('himerosApp',[])
.config(['$routeProvider',function($routeProvider){
$routeProvider
.when('/index', {
templateUrl: 'templates/welcome.html'
})
.when('/products/aerosois', {
templateUrl: 'templates/products.html',
controller: 'ProductController',
resolve: {
messages: function (productService) {
return productService.getProducts();
}
}
})
.when('/social', {
templateUrl: 'templates/social.html'
})
.otherwise({
redirectTo: '/index'
});
}]);
product-controller.js
'use strict';
angular.module('himerosApp')
.controller("ProductController", ['$scope','messages',
function($scope, messages ) {
$scope.products = messages;
}]);
product-service.js
angular.module('himerosApp')
.service("productService",['$http','$q',
function( $http, $q ) {
this.getProducts = function() {
return $http.get("/products").then(
function( response ) {
return response.data;
},
function( response ) {
if(!angular.isObject( response.data ) ) {
console.log('unknown error');
return ( $q.reject( "An unknown error ocurred." ) );
}
console.log(response.data.message);
return ( $q.reject( response.data.message ) );
}
);
};
return {
getProducts : this.getProducts
};
}]);
提前致谢!
【问题讨论】:
-
值得注意的是,当我调试代码时,我可以看到消息和 $scope.products 数组被填充。当我查看生成的页面时,我看到很多由 ng-repeat (100+) 创建的空 div,这是错误的,因为请求的返回是 5 个元素的数组。
标签: angularjs http ng-repeat resolve ng-view