Skip to content

Instantly share code, notes, and snippets.

@misterzik
Last active August 29, 2015 14:25
Show Gist options
  • Save misterzik/2a43304a09e424fc7c19 to your computer and use it in GitHub Desktop.
Save misterzik/2a43304a09e424fc7c19 to your computer and use it in GitHub Desktop.
How to use HTTP.GET in AngularJS correctly? (Dynamically)
=================================================================
This is a directive saved in a different folder:
=================================================================
'use strict';
todoApp.factory('eventData', function($http, $q){
return {
getEvent: function(id){
var deferred = $q.defer();
// I added the extension '.json' after ID to only pick json.
$http({method: 'GET', url: '/data/phonebook/'+id+'.json'}).
success(function (data, status, headers, config){
deferred.resolve(data);
}).
error(function (data, status, headers, config){
deferred.reject(status);
});
return deferred.promise;
}
};
});
=================================================================
This is a controller saved in a different section:
=================================================================
'user strict';
todoApp.controller('FeederController',
function FeederController($scope, eventData) {
$scope.events =[ ];
for (var i=1; i<2; i++){
eventData.getEvent(i).then(
function (event){$scope.events.push(event);},
function (statusCode) {console.log(statusCode)});
}
}
);
=================================================================
This is my json File located on /data/phonebook/1.json :
=================================================================
{"name": "John Foo",
"id": 1,
"phone": "201-555-6666",
"ext": "123",
"departs": "Automation"
}
=================================================================
This is my .html File :
=================================================================
<table class="table table-striped">
<tr>
<td>
Name
</td>
<td>
Phone #
</td>
<td>
Ext #
</td>
<td>
Department
</td>
</tr>
<tr ng-repeat="event in events | orderBy: 'name'">
<td>
{{event.name}}
</td>
<td>
{{event.phone}}
</td>
<td>
{{event.ext}}
</td>
<td>
{{event.departs}}
</td>
</tr>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment