标签:watch service char app log ati time oct body
在 AngularJS 中,服务是一个函数或对象,可在你的 AngularJS 应用中使用。
AngularJS 内建了30 多个服务。
在很多服务中,比如 $location 服务,它可以使用 DOM 中存在的对象,类似 window.location 对象
因为这些服务可以获取到Angular应用声明周期的每一个阶段,并且和$watch整合,让Angular可以监控应用,处理事件变化。普通的DOM对象则不能在Angular应用声明周期中和应用整合。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="angular-1.6.3/angular.js"></script> </head> <body> <div ng-app="myApp" ng-controller="myCtrl"> <div ng-app="myApp" ng-controller="myCtrl"> <p>现在时间是:</p> <h1>{{theTime}}</h1> </div> <p>$interval 访问在指定的周期(以毫秒计)来调用函数或计算表达式。</p> </div> <script> var app = angular.module(‘myApp‘, []); app.controller(‘myCtrl‘, function($scope,$interval) { $scope.theTime = new Date().toLocaleTimeString(); $interval(function () { $scope.theTime= new Date().toLocaleTimeString(); },1000); }); </script> </body> </html>
你可以创建访问自定义服务,链接到你的模块中:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="angular-1.6.3/angular.js"></script> </head> <body> <div ng-app="myApp" ng-controller="myCtrl"> <p>255 的16进制是:</p> <h1>{{hex}}</h1> </div> <p>自定义服务,用于转换16进制数:</p> <script> var app = angular.module(‘myApp‘, []); app.service(‘heaxfy‘,function () { this.myFunc = function (x) { return x.toString(16); } }); app.controller(‘myCtrl‘, function($scope,heaxfy) { $scope.hex = heaxfy.myFunc(255); }); </script> </body> </html>
$watch:持续监听数据上的变化,更新界面,如:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="angular-1.6.3/angular.js"></script> </head> <body> <div ng-app="myApp" ng-controller="myCtrl"> <b>请输入姓名:</b><br> <b>姓:</b><input type="text" ng-model="lastName"><br> <b>名:</b><input type="text" ng-model="firstName"><br> <h1>{{ lastName + " " + firstName }}</h1> <h2>{{ fullName }}</h2> </div> <script> var app = angular.module(‘myApp‘, []); app.controller(‘myCtrl‘, function($scope) { $scope.lastName = ""; $scope.firstName = ""; //监听lastName的变化,更新fullName $scope.$watch(‘lastName‘, function() { $scope.fullName = $scope.lastName + " " + $scope.firstName; }); //监听firstName的变化,更新fullName $scope.$watch(‘firstName‘, function() { $scope.fullName = $scope.lastName + " " + $scope.firstName; }); }); </script> </body> </html>
标签:watch service char app log ati time oct body
原文地址:http://www.cnblogs.com/dehuachenyunfei/p/6628623.html