Angular.jsのサービスの中から、value・factory・serviceの実装を試してみます。
value
HTML
<div ng-controller="myCtrl">
<div>{{message}}</div>
<div>{{object.key1}}</div>
<div>{{testFunction}}</div>
</div>
JavaScript
var app = angular.module('app', []);
// 文字列
app.value('message', 'おはよう');
// オブジェクト
app.value('object', {
key1: 'value1',
key2: 'value2',
key3: 'value3'
});
// 関数
app.value('testFunction', function(name) {
return 'Hi! ' + name;
});
app.controller('myCtrl', ['$scope', 'message', 'object', 'testFunction', function($scope, message, object, testFunction) {
$scope.message = message;
$scope.object = object;
$scope.testFunction = testFunction('Suzuki');
}]);
| value(‘name‘, ‘object‘) | nameにサービス名、objectに文字列やオブジェクト・関数などサービスの内容を指定。 |
|---|
factory
HTML
<div ng-controller="myCtrl">
<div>{{message}}</div>
<div>{{object.key2}}</div>
<div>{{testFunction}}</div>
</div>
JavaScript
var app = angular.module('app', []);
app.factory('myFactory', function() {
var service = {};
// 文字列
service.message = 'こんにちは';
// オブジェクト
service.object = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
};
// 関数
service.testFunction = function(name) {
return 'Hi! ' + name;
};
return service;
});
app.controller('myCtrl', ['$scope', 'myFactory', function($scope, myFactory) {
$scope.message = myFactory.message;
$scope.object = myFactory.object;
$scope.testFunction = myFactory.testFunction('Satoh');
}]);
| factory(‘name‘, ‘function‘) | nameにサービス名、functionにサービスのインスタンスを取得する関数を指定。 |
|---|
service
HTML
<div ng-controller="myCtrl">
<div>{{message}}</div>
<div>{{object.key3}}</div>
<div>{{testFunction}}</div>
</div>
JavaScript
var app = angular.module('app', []);
app.service('myService', function() {
// 文字列
this.message = 'こんばんは';
// オブジェクト
this.object = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
};
// 関数
this.testFunction = function(name) {
return 'Hi! ' + name;
};
});
app.controller('myCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.message = myService.message;
$scope.object = myService.object;
$scope.testFunction = myService.testFunction('Tanaka');
}]);
| service(‘name‘, ‘function‘) | nameにサービス名、functionにサービスのコンストラクタ関数を指定。 |
|---|
コメントが承認されるまで時間がかかります。