Getting JSON data from factory Getting JSON data from factory json json

Getting JSON data from factory


controller.js

.controller('DashCtrl',function($scope, Noticias) {    Noticias.all(function(data){        $scope.noticias = data;    });});

service

 .factory('Noticias', function($http) {  return {    all: function(callback) {        $http.get('noticias.json').success(function(data)        {           callback(data);        });    },    get: function(noticiaId) {      for (var i = 0; i < noticias.length; i++) {        if (noticias[i].id === parseInt(noticiaId)) {          return noticias[i];        }      }      return null;    }  };});

Essentially your web call takes time and you asked for the array instantly. By passing a callback in your asking it for the data when its done.

edit: As for your get function this would likely need another json endpoint that accepts a parameter of noticiaid so that the server can pre-filter the data. If the dataset is not large you could use an angular filter and cache your result set from the factory.

Storing Objects in HTML5 localStorage (client cache example if you dont want server filtering but has limitations)


It's exactly as @Lee Winter said, since JavaScript is asynchronously you code will not wait for the JSON data to be loaded.

My suggestion would be to use a promise like so

Factory

.factory('Noticias', function($http) {     var noticias;    function all()  {    // use 'then' instead of 'success'    return $http.get('jsonfile').then(function(response)     {      // hold data in factory variable       noticias = response.data;      // return data to caller      return response.data;    });  }    function find(id) {    var i;     for(i = 0; i < noticias.length; i++)    {      if(noticias[i].id === id)        return noticias[i];    }        return null;  }    return {    all: all,    find: find  }});