使用angularJS通过$ http加载Json时出现问题

时间:2015-07-25 15:28:39

标签: json angularjs angular-ui-router

我试图在联系人应用程序中加载Json时遇到问题。 (基于角度UI)

我是AngularJS的新手,我不知道错误在哪里(好吧,是的,控制台说法'语法错误:意外的令牌i')

var myapp = angular.module('myapp', ["ui.router"])
    myapp.config(function($stateProvider, $urlRouterProvider){

      $urlRouterProvider.when("", "/contacts/list");
      $urlRouterProvider.when("/", "/contacts/list");

      // For any unmatched url, send to /route1
      $urlRouterProvider.otherwise("/contacts/list");

      $stateProvider
        .state('contacts', {
            abstract: true,
            url: '/contacts',
            templateUrl: 'contacts.html',
            controller: 'contactController',
            onEnter: function(){
              console.log("enter contacts");
            }

        })
        .state('contacts.list', {
            url: '/list',
            // loaded into ui-view of parent's template
            templateUrl: 'contacts.list.html',
            onEnter: function(){
              console.log("enter contacts.list");
            }
        })
        .state('contacts.detail', {
            url: '/:id',
            // loaded into ui-view of parent's template
            templateUrl: 'contacts.detail.html',
            controller: function($scope, $stateParams){
              $scope.person = $scope.contacts[$stateParams.id];
            },
            onEnter: function(){
              console.log("enter contacts.detail");
            }
        })
        .state('contacts.detail.test', {
            url: '/test',
            // loaded into ui-view of parent's template
            templateUrl: 'contacts.detail.test.html',
            onEnter: function(){
              console.log("enter contacts.detail.text");
            }
        });
    });

    myapp.controller('contactController',function($scope, $http){
    $scope.contacts = []; //declare an empty array
    $http.get("contacts.json")
    .success(function(response){ 
        $scope.contacts = response;  //ajax request to fetch data into $scope.data
    });
});

contacts.json的内容:

[{ id:0, name: "Alice" }, 
{ id:2, name: "Alirce" },
{ id:3, name: "Alwicse" },
{ id:4, name: "Awlice" },
{ id:1, name: "Bob" }]

我做了一个Plunkr来解释它

1 个答案:

答案 0 :(得分:0)

正如大家在评论中所说,JSON键必须是字符串。将contacts.json替换为

[
    { "id":0, "name": "Alice" }, 
    { "id":2, "name": "Alirce" },
    { "id":3, "name": "Alwicse" },
    { "id":4, "name": "Awlice" },
    { "id":1, "name": "Bob" }
]

这是一个固定的Plunkr