angularjs service 自定义服务

在学习service之前,我们应该了解这个“service”是用来干嘛的。其实,这个service就好比如现实生活中的“服务”,例如:理发服务、洗脚服务……那么angularjs的服务有是干嘛的呢?在 AngularJS 中,服务是一个函数或对象,可在你的 AngularJS 应用中使用。AngularJS 内建了30 多个服务(比如:$location 服务,它可以返回当前页面的 URL 地址)。

angularjs常用的内置服务

名称 作用
$http 向服务器发送请求,响应服务器传送过来的数据。
$location 增强 window.location 对象的功能
$q 创建一个promise对象,处理异步回调嵌套
$timeout 等价于window.setTimeout
$interval 等价于window.setInterval

自定义服务

简单案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title>angularjs service</title>
    <meta name="author" content="loushengyue">
</head>
<body>

<div ng-app="app" ng-controller="ctrl">
    <div ng-repeat="item in fruits">
        名称:<span ng-bind="item.name"></span> |
        单价:<span ng-bind="item.price"></span> |
        数量:<span ng-bind="item.num"></span>
    </div>
    总价:<span ng-bind="total"></span>
</div>

<script src="https://cdn.bootcss.com/angular.js/1.6.9/angular.min.js"></script>
<script>
    angular.module('app', [])
        .controller('ctrl', ['$scope', 'mathService', function ($scope, mathService) {
            //内置服务通常带有"$",而自定义服务通常不加"$",
            $scope.fruits = mathService.data;
            $scope.total = mathService.getTotal();
            //记住,服务提供的是原始数据或方法,它不会更新,所以没有双向绑定
        }])
        .service('mathService', function () {
            this.data = [
                {id: 1, name: 'apple', price: 5, num: 8},
                {id: 2, name: 'banana', price: 4, num: 10}
            ];
            this.getTotal = function () {
                var total = 0;
                angular.forEach(this.data, function (item) {
                    total += item.price * item.num;
                });
                return total;
            };
            return this;
        })
</script>
</body>
</html>

普通案例:

<div ng-app="app" ng-controller="ctrl">
    <input type="text" ng-model="usercode" ng-keyup="checkCode()">
    <span ng-bind="code" ng-click="changeCode()" style="cursor: pointer;"></span><br>
    验证结果:<span ng-bind="result"></span>
</div>

<script src="https://cdn.bootcss.com/angular.js/1.6.9/angular.min.js"></script>
<script>
    angular.module('app', [])
        .controller('ctrl', ['$scope', 'codeApi', function ($scope, codeApi) {
            $scope.code = codeApi.getCode();
            $scope.changeCode = function () {
                this.code = codeApi.getCode();
            };
            $scope.checkCode = function () {
                this.result = angular.lowercase(this.code) === angular.lowercase(this.usercode);
            }
        }])
        .service('codeApi', function () {
            this.getCode = function () {
                var codeStr = 'abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ0123456789',
                    len = codeStr.length,
                    str = '',
                    max = Math.ceil(Math.random() * (6 - 4) + 4);
                for (var i = 1; i < max; i++) {
                    var index = Math.floor(Math.random() * len);
                    str += codeStr.substr(index, 1);
                }
                return str;
            };
            return this;
        })
</script>

高级案例:

注意:别忘了后面还有一个data.json文件

index.html

<div ng-app="app" ng-controller="ctrl">
    <ul>
        <li ng-repeat="item in data">
            名称:<span ng-bind="item.name"></span> |
            价钱:<span ng-bind="item.price"></span> |
            数量:<span ng-bind="item.num"></span>
        </li>
    </ul>
</div>

<script src="https://cdn.bootcss.com/angular.js/1.6.9/angular.min.js"></script>
<script>
    angular.module('app', [])
        .controller('ctrl', ['$scope', 'httpService', function ($scope, httpService) {
            $scope.data = [];
            httpService.getData('./data.json').then(function (value) {
                $scope.data = value;
            });
        }])
        .service('httpService', ['$http', '$q', function ($http, $q) {

            this.getData = function (url) {
                var res = $q.defer();
                this.httpRequestEvent('get', url).then(function (data) {
                    res.resolve(data);
                });
                return res.promise;
            };

            this.httpRequestEvent = function (type, url) {
                var res = $q.defer();
                $http({
                    method: type,
                    url: url
                }).then(function successCallback(response) {
                    res.resolve(response.data);
                }, function errorCallback(error) {
                    res.reject(error);
                });
                return res.promise;
            };
            return this;
        }]);
</script>

data.json

[
  {
    "id": 1,
    "name": "apple",
    "price": 10,
    "num": 5
  },
  {
    "id": 2,
    "name": "banana",
    "price": 8,
    "num": 10
  }
]

猜你喜欢

转载自blog.csdn.net/weixin_41424247/article/details/79823987
今日推荐