Created
December 7, 2014 12:23
-
-
Save saintc0d3r/4bb01ddd4237febcbf27 to your computer and use it in GitHub Desktop.
HOW TO - Create an AngularJS service by using $resource & factory method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> | |
<title></title> | |
<link href="css/style.css" rel="stylesheet"> | |
<!-- angularjs js --> | |
<script src="lib/angular/angular.js"></script> | |
<script src="lib/angular-resource/angular-resource.js"></script> | |
</head> | |
<body ng-app="awesomeapp"> | |
<div ng-controller="main_controller"> | |
<ul ng-repeat="item in items"> | |
<li> | |
<h2>{{item.title}}</h2> | |
<p>{{item.description}}</p> | |
<h2>{{(item.price|currency)}}</h2> | |
</li> | |
</ul> | |
</div> | |
</body> | |
<!-- App's JS --> | |
<script src="js/app.js"></script> | |
<script src="js/services/items-datasources.js"></script> | |
<script src="js/controllers/main-controller.js"></script> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('awesomeapp.services', ['ngResource']) | |
.factory('items_datasource', function($resource){ | |
var rest_endpoint = "http://localhost:3000/api"; | |
/** | |
* Pull all items from REST point. | |
*/ | |
this.get_all = function(callback){ | |
var items_resource = '/items'; | |
$resource(rest_endpoint+items_resource, {}).query(function(response){ | |
callback(response); | |
}); | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('awesomeapp.controllers', ['awesomeapp.services']) | |
.controller('main_controller', function($scope, items_datasource){ | |
$scope.items = function(){ | |
items_datasource.get_all(function(items){ | |
$scope.items = items; | |
}); | |
} | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment