1

I'm trying to make a simple angular app which reads json data , but in response I'm only getting "," not data.Any pointers where I m going wrong ? I have attached index.html and abc.json file that i m keepingat server PFB the code .

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 Answers 2

2

getStudents is asynchronous. You should retrieve and assign students through the callback handler.

  .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;
            });
            ...            
        })  
Sign up to request clarification or add additional context in comments.

3 Comments

ya its working but why result.data not only result ?
the full response object is passed to the .then handler which has the HTTP status (.status), and HTTP header (.headers), in addition to the payload (.data).
"stackoverflow.com/questions/27782567/…" ne pointers on this , why this is not working ?
2

Nearly right. getStudents in fact returns you a 'Promise', not the data itself. You have to use that Promise to get your data:

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

1 Comment

Sounds like you are wrapping your json in an extra layer called data (i.e. {data: {"name:...}}) on the server side

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.