Angular 专家您好!
我对表( implementation )使用了这个自定义指令,但是当我尝试使用 $http 服务从文件加载该 json 数组时,json 没有加载到 $scope.items 中,我是 Angular 和初学者关于相当先进的 javascript,因此我需要你的一些帮助。
Controller 初始化
fessmodule.controller('ptiListController', function($http, $scope, $filter) {
$http服务调用
$http.get('data/ptis/ptis.json').then(function(response) {
$scope.items = response.data;
}
);
浏览器控制台错误
TypeError: Cannot read property 'length' of undefined
at Scope.$scope.groupToPages (http://localhost:8000/app/modules/app/phone/scripts/pti-list-controller.js:75:49)
at Scope.$scope.search (http://localhost:8000/app/modules/app/phone/scripts/pti-list-controller.js:68:16)
at new <anonymous> (http://localhost:8000/app/modules/app/phone/scripts/pti-list-controller.js:117:12)
at invoke (http://localhost:8000/app/lib/js/angular.js:4185:17)
at Object.instantiate (http://localhost:8000/app/lib/js/angular.js:4193:27)
at http://localhost:8000/app/lib/js/angular.js:8462:28
at link (http://localhost:8000/app/lib/js/angular-route.js:975:26)
at invokeLinkFn (http://localhost:8000/app/lib/js/angular.js:8219:9)
at nodeLinkFn (http://localhost:8000/app/lib/js/angular.js:7729:11)
at compositeLinkFn (http://localhost:8000/app/lib/js/angular.js:7078:13) <div ng-view="" class="ng-scope">
所以我对 fiddle 的改变是:
而不是:
$scope.items = [
{"id":1,"name":"name 1","description":"description 1","field3":"field3 1","field4":"field4 1","field5 ":"field5 1"},
{"id":2,"name":"name 2","description":"description 1","field3":"field3 2","field4":"field4 2","field5 ":"field5 2"},
{"id":3,"name":"name 3","description":"description 1","field3":"field3 3","field4":"field4 3","field5 ":"field5 3"}
];
我已更改为:
$http.get('data/ptis/ptis.json').then(function(response) {
$scope.items = response.data;
}
);
而且,我尝试使用服务调用:
$http.get('data/ptis/ptis.json').success(function(data) {
$scope.items = data;
});
并得到相同的行为。
提前谢谢您!
最佳答案
我相信您使用的$http.get
是错误的。尝试 $http.JSONP
这种模式:
$scope.items = {}; // <-- initialize empty object
$http.jsonp('/someJSONUrl').
success(function(data) {
// this callback will be called asynchronously
// when the response is available
$scope.items = data; // <-- fill object with data
});
在保存一些数据之前,您不能使用$scope.items
。这就是为什么你必须首先初始化它,作为空对象/数组,然后用数据填充它,而 Angular
魔术应该完成剩下的工作:)
关于javascript - Angular $http 服务不加载 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29072992/