javascript - Angular $http 服务不加载 json 文件

标签 javascript json angularjs

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/

相关文章:

javascript - Angular js - 缓存 rootScope 参数及其值

javascript - Angular ng-显示如何使其可见

javascript - 如何在 Socket.IO 中取消、超时或清除排队消息

c# - 使用 DataContractJsonSerializer 将元素附加到文件中的 JSON 数组

javascript - 使用 AngularJS 时如何根据选项值而不是索引选择默认选择选项?

json - 在Dart中将数据添加到JSON文件

arrays - 从数组结构呈现 json 的问题

javascript - 为什么这些日历 javascript 隐藏 IE 的 select、applet 和 iframe 标记?

javascript - 查找 VS Code 中的所有引用无法在整个项目中工作

javascript - Selenium Webdriver 执行由于 javascript 等待条件而卡住