AngularJS学习篇(八)

AngularJS 服务(Service)

在 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>

 

相关文章