angularjs service Custom Service

Keywords: angular AngularJS JSON

order

Before learning service, we should understand what the "service" is used for. In fact, this service is just like the "service" in real life, such as: hairdressing service, foot washing service So what are the services of AngularJS? In AngularJS, a service is a function or object that can be used in your AngularJS application. AngularJS has built in more than 30 services (for example, $location service, which can return the URL address of the current page).

Commonly used built-in services of angularjs

Name Effect
$http Send a request to the server in response to the data sent by the server.
$location Enhance the function of window.location object
$q Create a promise object to handle asynchronous callback nesting
$timeout Equivalent to window.setTimeout
$interval Equivalent to window.setInterval

Custom service

Simple case:

<!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">
        //Name:<span ng-bind="item.name"></span> |
        //Unit Price:<span ng-bind="item.price"></span> |
        //Number:<span ng-bind="item.num"></span>
    </div>
    //Total price:<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) {
            //Built in services usually have "$", while custom services usually do not add "$",
            $scope.fruits = mathService.data;
            $scope.total = mathService.getTotal();
            //Remember, a service provides raw data or methods, which are not updated, so there is no two-way binding
        }])
        .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>

General case:

<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>
    //Verification results:<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>

Advanced case:

Note: don't forget that there is also a data.json file

index.html

<div ng-app="app" ng-controller="ctrl">
    <ul>
        <li ng-repeat="item in data">
            //Name:<span ng-bind="item.name"></span> |
            //Price:<span ng-bind="item.price"></span> |
            //Number:<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
  }
]

Posted by Tainted Kitten on Sun, 05 Apr 2020 08:26:52 -0700