2015-01-04 126 views
1

我想做一個簡單的角度應用程序,它讀取JSON數據,但作爲迴應,我只得到「,」而不是data.Any指向哪裏我會出錯?我已附加index.html和abc.json文件,我保持服務器 PFB的代碼。角Js讓Json不工作

HTML:

<body ng-app="sampleApp" ng-controller="ctrl1"> 
    Name:<input type="text" ng-model="name"> 
    <ul> 
     <li ng-repeat="student in students | filter:name">{{student.name +","+student.empNo}</li> 
    </ul> 
    Name:<input type="text" ng-model="newname"> 
    EmpNo:<input type="text" ng-model="newemp"> 
    <input type="button" value="AddMe" ng-click="add()"/> 
    <div> 
     <div ng-view></div> 
    </div> 

的Javascript:

var x=angular.module('sampleApp',[]) 
.factory("simpleFactory",function($http){ 
    var factory={}; 
    factory.getStudents=function(){ 
     return $http.get("abc.json"); 
    } 
     return factory; 
    }) 
    .controller("ctrl1",function($scope,simpleFactory){ 
     $scope.students=simpleFactory.getStudents(); 
     $scope.add=function(){ 
     $scope.students.push(
      { 
      name:$scope.newname,empNo:$scope.newemp 
      }  
     ) 
    } 
}) 

abc.json

[   
    {"name":"jack","empNo":"1"}, 
    {"name":"Red","empNo":"2"}, 
    {"name":"Jill","empNo":"3"} 
] 

回答

2

getStudents是異步的。您應該通過回調處理程序檢索並分配學生。

.factory("simpleFactory",function($http){ 
      var factory={}; 
      factory.getStudents = $http.get("abc.json"); 
      return factory; 
     }) 
     .controller("ctrl1",function($scope,simpleFactory){ 
      simpleFactory.getStudents().then(function(result) { 
        $scope.students= result.data; 
      }); 
      ...    
     }) 
+0

ya其工作,但爲什麼result.data不僅導致? – Aditya

+0

除了有效負載(.data)之外,完整響應對象還會傳遞給具有HTTP狀態(.status)和HTTP標頭(.headers)的.then處理程序。 – pixelbits

+0

「http://stackoverflow.com/questions/27782567/angular-resource-is-not-working/27782995#27782995」ne指針在這,爲什麼這不工作? – Aditya

2

差不多。事實上,你會得到'承諾',而不是數據本身。您必須使用該Promise來獲取您的數據:

simpleFactory.getStudents().then(function(data) { 
    $scope.students=data 
    // $scope.students=data.data  // you may need this given your feedback 
}); 
+0

它還沒有工作,result.data正在工作:/ – Aditya

+0

聽起來像你正在包裝你的JSON在一個額外的圖層稱爲數據(即{數據:{「名稱:...}})在服務器端 –