AngularJS - Basic
Factories, Services and Providers
by Ryan Morris
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<div class="container" ng-app="myApp">
<div ng-controller="MainCtrl">
<h1>Forms</h1>
<div ng-show="data.items.length">
<p>To do items:</p>
<ul>
<li ng-repeat="item in data.items">
{{item.title}}
<!-- Ability to remove an item from the list
<a href="#" ng-click="removeItem($index)">Remove</a>
-->
</li>
</ul>
</div>
<form name="itemForm" ng-submit="submitForm()">
<div class="form-group">
<input type="text" ng-model="item.title" name="title" placeholder="Title" class="form-control" required ng-minlength="3" />
<span ng-show="itemForm.title.$invalid">
This title is not valid.
</span>
<span ng-show="itemForm.title.$error.required">
Please enter a title.
</span>
<span ng-show="itemForm.title.$error.minlength">
Title must be at least 3 characters long.
</span>
</div>
<div class="form-group">
<label>Description</label>
<textarea ng-model="item.description" name="description" class="form-control" ></textarea>
</div>
<div class="form-group">
<label>Due on</label>
<input type="date" ng-model="item.duedate" name="duedate" class="form-control" />
</div>
<div...
CSS
div[ng-controller] {
border: 1px solid #ccc;
border-radius:5px;
margin:5px 0;
padding:5px;
}
div[ng-controller] > div[ng-controller] {
background-color:#f0f0f0;
}
.ng-dirty .ng-invalid{
border:1px solid red;
}
.form-group span{
color:red;
}
.ng-pristine span{
display:none; /* force hides */
}
.ng-dirty.ng-invalid-required{
background-color:lightpink;
}
.ng-dirty.ng-valid{
border-color:green;
}
JavaScript
var myApp = angular.module('myApp', []);
// Service is defined as a class function
// Angular will perform "new" to instantiate this guy
myApp.service('ServiceItemService', [function() {
var items = [];
this.list = function() {
return items;
}
this.add = function(item) {
items.push(item);
}
}]);
// Service is defined as an object
myApp.factory('FactoryItemService', [function() {
var items = [];
return {
get: function(i) {
return data[i];
},
add: function(item) {
items.push(item);
},
list: function() {
return items;
}
};
}]);
myApp.controller('MainCtrl', ['ServiceItemService', '$scope', function(ItemService, $scope) {
$scope.data = {
items: ItemService.list()
};
// form submission handler
$scope.submitForm = function() {
// add new todo item
ItemService.add($scope.item);
// flush the form
$scope.item = {};
$scope.itemForm.$setPristine();
}
/*// Ability to remove an item from the list
$scope.removeItem = function(index) {
$scope.data.items.splice(index, 1);
};*/
}]);