Factory vs Service
angularjs factory vs service do the same thing, just a different way of instantiation
HTML
<script src="http://code.angularjs.org/angular-1.0.0rc9.js"></script>
<div ng-controller="InputCtrl">
<h2>Input</h2>
<form ng-submit="addInput()">
<input type="text" ng-model="input.name" size="30"
placeholder="输入员工姓名">
<input type="number" ng-model="input.age" size="30"
placeholder="输入员工年龄">
<input type="text" ng-model="input.title" size="30"
placeholder="输入员工职位">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
<br />
<div ng-controller="OutputCtrl">
<h2>Output</h2>
<ul>
<li ng-repeat="p in persons.list">
{{p.name}}, {{p.age}}, {{p.title}}
</li>
</ul>
</div>
JavaScript
var app = angular.module('myApp', []);
app.factory('testFactory', function(){
var testObject = {};
testObject.list = [];
var _setter = function (data) {
testObject.list.push(data);
};
var _getter = function () {
return testObject;
};
return {
setter: _setter,
getter: _getter
}
});
function InputCtrl($scope, testFactory)
{
$scope.input = {
name: '',
age: null,
title: ''
};
$scope.addInput = function() {
testFactory.setter($scope.input);
$scope.input = {
name: '',
age: null,
title: ''
};
};
}
function OutputCtrl($scope, testFactory)
{
$scope.persons = testFactory.getter();
}