Services
Angular services are substitutable objects that are wired together using dependency
injection (DI). You can use services to organize and share code across your app.
Angular services are:
- Lazily instantiated – Angular only instantiates a service when an application component depends on it.
- Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
Angular offers several useful services (like
$http), but for most applications
you'll also want to create your own.Using a Service
To use an Angular service, you add it as a dependency for the component (controller, service,
filter or directive) that depends on the service. Angular's dependency injection
subsystem takes care of the rest.
-----------------------
index.html
-----------------------
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example45-production</title>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example45-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular.min.js"></script>
<script src="script.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myServiceModule">
<div id="simple" ng-controller="MyController">
<p>Let's try this simple notify service, injected into the controller...</p>
<input ng-init="message='test'" ng-model="message" >
<button ng-click="callNotify(message);">NOTIFY</button>
<p>(you have to click 3 times to see an alert)</p>
</div>
</body>
</html>
<body ng-app="myServiceModule">
<div id="simple" ng-controller="MyController">
<p>Let's try this simple notify service, injected into the controller...</p>
<input ng-init="message='test'" ng-model="message" >
<button ng-click="callNotify(message);">NOTIFY</button>
<p>(you have to click 3 times to see an alert)</p>
</div>
</body>
</html>
-------------------------
script.js
-------------------------
(function(angular) {
'use strict';
angular.
module('myServiceModule', []).
controller('MyController', ['$scope','notify', function ($scope, notify) {
$scope.callNotify = function(msg) {
notify(msg);
};
}]).
factory('notify', ['$window', function(win) {
var msgs = [];
return function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);
})(window.angular);
$exceptionHandler
$http
$route
$scope
'use strict';
angular.
module('myServiceModule', []).
controller('MyController', ['$scope','notify', function ($scope, notify) {
$scope.callNotify = function(msg) {
notify(msg);
};
}]).
factory('notify', ['$window', function(win) {
var msgs = [];
return function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);
})(window.angular);
Some Sample service in Angular JS
$log
$exceptionHandler
$http
$route
$scope
No comments:
Post a Comment