AngularJS service sample
AngularJSのserviceを利用したサンプル。
by Shuya Tsukamoto
HTML
<div ng-app="myApp">
<div ng-controller="myCtrl1">
<p>商品名</p>
<input type="text" ng-model="itemService.name"></input>
<p>税別価格(円)</p>
<input type="text" ng-model="itemService.price"></input>
<p>※以下の税込価格は1円未満は切捨てです。</div>
<hr>
<div ng-controller="myCtrl2">
<h3>2014/3/31までの税込価格</h3>
<p>商品名 = {{itemService.getItemName()}}</p>
<p>商品価格(税込5%) = {{itemService.priceWithTax(1.05)}}</p>
<hr>
<h3>2014/4/1から2015/9/30までの税込価格</h3>
<p>商品名 = {{itemService.getItemName()}}</p>
<p>商品価格(税込8%) = {{itemService.priceWithTax(1.08)}}</p>
<hr>
<h3>2015/10/1からの税込価格</h3>
<p>商品名 = {{itemService.getItemName()}}</p>
<p>商品価格(税込10%) = {{itemService.priceWithTax(1.10)}}</p>
</div>
</div>
JavaScript
var myApp = angular.module("myApp", []);
myApp.service('itemService', function () {
return {
name: undefined,
price: 0,
getItemName: function () {
return this.name;
},
priceWithTax: function (tax) {
return Math.floor(this.price * tax);
}
};
});
myApp.controller("myCtrl1", ['$scope', 'itemService', function ($scope, itemService) {
$scope.itemService = itemService;
}]);
myApp.controller("myCtrl2", ['$scope', 'itemService', function ($scope, itemService) {
$scope.itemService = itemService;
}]);