var app = angular.module('blogApp', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
/* implementation 1 with service */
/*
app.service("Posts", function() {
this.getAll = function() {
return [{title: "hello world"},
{title: "post no 2"},
{title: "last post"}];
}
});
*/
/* implementation 2 with factory */
app.factory("Posts", function() {
var fac = {};
fac.getAll = function() {
return [{title: "hello world"},
{title: "post no 2"},
{title: "last post"}];
}
return fac;
});
app.controller('postCtrl', function($scope, Posts) {
$scope.posts = Posts.getAll();
});
<!DOCTYPE html>
<html ng-app="blogApp">
<head>
<meta charset="utf-8" />
<title>AngularJS factory</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link href="style.css" rel="stylesheet" />
<script data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js" data-require="angular.js@1.2.x"></script>
<script src="app.js"></script>
</head>
<body>
This is an example for angularjs service and factory.
<div ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
</div>
<div ng-controller="postCtrl">
<ul>
<li ng-repeat="post in posts">{{post.title}}</li>
</ul>
</div>
</body>
</html>
/* Put your css in here */
li {
font-size: 15px;
color: #11a;
}