Reputation: 3830
Currently I have the following service which populates a table elsewhere in my angular app.
Updated:
'use strict';
angular.module('projyApp')
.service('data', function data() {
// AngularJS will instantiate a singleton by calling "new" on this function
var getAllPeeps = function () {
return peeps;
}
var insertPeep = function(peep) {
peeps.push(peep);
}
var getPeep = function(peep) {
var foundPeep;
if (peep.firstname) {
peeps.forEach(function (pps){
if (pps.firstname == peep.firstname) {
foundPeep = pps;
}
});
} else if (peep.lastname) {
peeps.forEach(function (pps){
if (pps.lastname == peep.lastname) {
foundPeep = pps;
}
});
} else if (peep.inumber) {
peeps.forEach(function (pps) {
if (pps.inumber == peep.tagid) {
foundPeep = pps;
}
});
}
if (foundPeep) {
return foundPeep;
} else {
return "Error";
}
}
var getDataFromServer = function () {
//Fake it.
var peeps = [
{firstname:'Buster', lastname:'Bluth', tagid:'01'},
{firstname:'John', lastname:'McClane', tagid:'02'},
{firstname:'Mister', lastname:'Spock', tagid:'03'}
];
return peeps;
}
var peeps = getDataFromServer();
return {
getAllPeeps : getAllPeeps,
insertPeep : insertPeep,
getPeep : getPeep
}
});
Obviously this works, however I want the 'peeps' array to hold objects from an external json file.
How can I maintain functionality while loading the 'peeps' from an external json file like so:
$http.get("../../TestData/peeps.json").success(function(data) {
});
Upvotes: 1
Views: 2150
Reputation: 15876
function myController($scope, $http){
$http.get(url).success(function(data){ $scope.people = data; });
}
Upvotes: 0
Reputation: 1294
Usually I return the $http promise in angular. And the caller from the service can use success to do whatever it wants. But to maintain backwards compability, you can try this:
var getDataFromServer = function () {
var peeps = [];
$http.get("../../TestData/peeps.json").success(function(data) {
peeps.push.apply(peeps,data);
});
return peeps;
}
So you'll return a initially empty array. But it'll be filled with the json array.
Upvotes: 0
Reputation: 105
Angular does 2 way binding from the get go. So if you have a
$scope.var = function() {
$http.get(blah).success($scope.peeps = data.peeps;);
};
It will update the $scope.peeps on your view. $scope.var being a button generally.
Upvotes: 1