AngularJS Services (Service)
In AngularJS, a service is a function or object that can be used in your AngularJS app.
More than 30 services are built in AngularJS.
Why use the service?
In many services, such as $location service, it can use objects that exist in the DOM, like Window.location objects
Because these services can get to every stage of the angular application declaration cycle and integrate with $watch, angular can monitor the application and handle event changes. Normal DOM objects are not angular application declaration cycles and application consolidation.
<!DOCTYPE HTML><HTML><Head> <MetaCharSet= "Utf-8"> <Scriptsrc= "Angular-1.6.3/angular.js"></Script></Head><Body><DivNg-app= "MYAPP"Ng-controller= "Myctrl"> <DivNg-app= "MYAPP"Ng-controller= "Myctrl"> <P>Now the time is:</P> <H1>{{Thetime}}</H1> </Div> <P>$interval access invokes a function or evaluates an expression in the specified period (in milliseconds).</P></Div><Script> varapp=Angular.module ('myApp', []); App.controller ('Myctrl', function($scope, $interval) {$scope. Thetime= NewDate (). tolocaletimestring (); $interval (function() {$scope. Thetime= NewDate (). tolocaletimestring (); }, +); });</Script></Body></HTML>Create a custom Service
You can create access to custom services that are linked to your module:
<!DOCTYPE HTML><HTML><Head> <MetaCharSet= "Utf-8"> <Scriptsrc= "Angular-1.6.3/angular.js"></Script></Head><Body><DivNg-app= "MYAPP"Ng-controller= "Myctrl"> <P>255 of the 16 binary is:</P> <H1>{{Hex}}</H1></Div><P>Custom service for converting 16 binary numbers:</P><Script> varapp=Angular.module ('myApp', []); App.service ('Heaxfy',function () { This. MyFunc= function(x) {returnx.tostring ( -); } }); App.controller ('Myctrl', function($scope, heaxfy) {$scope. Hex=Heaxfy.myfunc (255); });</Script></Body></HTML>
$watch: continuously monitor changes on the data, update the interface, such as:
<!DOCTYPE HTML><HTML><Head> <MetaCharSet= "Utf-8"> <Scriptsrc= "Angular-1.6.3/angular.js"></Script></Head><Body><DivNg-app= "MYAPP"Ng-controller= "Myctrl"> <b>Please enter your name:</b><BR> <b>Name:</b><inputtype= "text"Ng-model= "LastName"><BR> <b>Name:</b><inputtype= "text"Ng-model= "FirstName"><BR> <H1>{{lastName + "" + FirstName}}</H1> <H2>{{FullName}}</H2></Div><Script> varapp=Angular.module ('myApp', []); App.controller ('Myctrl', function($scope) {$scope. LastName= ""; $scope. FirstName= ""; //Monitor LastName changes, update FullName$scope. $watch ('LastName', function() {$scope. FullName=$scope. LastName+ " " +$scope. FirstName; }); //Monitor firstname changes, update fullname$scope. $watch ('FirstName', function() {$scope. FullName=$scope. LastName+ " " +$scope. FirstName; }); });</Script></Body></HTML>
Angularjs Study Chapter (eight)