AngularJS创建自己的Service

半兽人 发表于: 2018-10-02   最后更新时间: 2018-10-02 20:39:20  
{{totalSubscript}} 订阅, 3,003 游览

创建自己的Service

html

<html ng-app="MyServiceApp">

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="framework/bootstrap-3.0.0/css/bootstrap.css">
    <script src="framework/angular-1.3.0.14/angular.js"><//script>
    <script src="MyService1.js"><//script>
</head>

<body>
    <div ng-controller="ServiceController">
        <label>用户名</label>
        <input type="text" ng-model="username" placeholder="请输入用户名" />
        <pre ng-show="username">{{users}}</pre>
    </div>
</body>

</html>

js

var myServiceApp = angular.module("MyServiceApp", []);
myServiceApp.factory('userListService', ['$http', function($http) {
        var doRequest = function(username, path) {
            return $http({
                method: 'GET',
                url: 'users.json'
            });
        }
        return {
            userList: function(username) {
                return doRequest(username, 'userList');
            }
        };
    }
]);

myServiceApp.controller('ServiceController', ['$scope', '$timeout', 'userListService',
    function($scope, $timeout, userListService) {
        var timeout;
        $scope.$watch('username', function(newUserName) {
            if (newUserName) {
                if (timeout) {
                    $timeout.cancel(timeout);
                }
                timeout = $timeout(function() {
                    userListService.userList(newUserName)
                        .success(function(data, status) {
                            $scope.users = data;
                        });
                }, 350);
            }
        });
    }
]);

data.json

[{
    "name": "《用AngularJS开发下一代WEB应用》"
},{
    "name": "《ORCHOME》"
},{
    "name": "《ActionScript3.0》"
}]

步骤

本例子通过input输入,然后向后台获取数据,进行展示。

  1. js中定义了一个userListService服务
  2. 利用$scope.$watch监控数据模型的变化,监听username。
  3. 当监听到新的newusername时,就会触发函数。
  4. 触发前,增加防抖动timeout,350毫秒不在有输入,才会请求后台

注意:

  1. 自己定义的服务,不要以$开头,会和AngularJS自身的容易混选
  2. 在服务注入的时候,先写AngularJS本身的服务,自己的放在后面
更新于 2018-10-02

查看AngularJS更多相关的文章或提一个关于AngularJS的问题,也可以与我们一起分享文章