AngularJS objects dependencies injection
HTML
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.angularjs.org/1.0.2/angular.min.js"></script>
<b>{{1+2}}</b>
<h1>Test</h1>
<div data-ng-controller="List">
<ul>
<li data-ng-bind="item.pretty()" data-ng-repeat="item in items"></li>
</ul>
</div>
<div data-ng-controller="NewItem">
<h2>Add a new item</h2>
<ol>
<li>
Name: <input data-ng-model="name" />
</li>
<li>
Price: <input data-ng-model="price" type="number" />
</li>
<li>
<input data-ng-click="addToList()" type="button" value="Add item" />
</li>
</ol>
</div>
JavaScript
"use strict";
var Item = function (name, price) {
var self = this;
self.name = name;
self.price = price;
self.pretty = function () {
return self.name + ": " + self.price;
};
};
var NewItem = function ($filter, $scope, communication) {
$scope.name = "";
$scope.price = "";
$scope.addToList = function () {
var item = new Item($scope.name, $scope.price);
communication.addItemToList(item);
$scope.name = "";
$scope.price = "";
};
};
var List = function ($scope, communication) {
$scope.items = [];
$scope.addItem = function (item) {
$scope.items.push(item);
};
communication.setList($scope);
};
angular.module("services", []).service("communication", function () {
var self = this;
return {
setList: function (list) {
self.list = list;
},
addItemToList: function (item) {
self.list.addItem(item);
}
};
});
$(document).ready(function () {
angular.bootstrap(document, ["services"]);
});