[java学习10]angularJS之服务练习

来源:互联网 发布:如何注销淘宝店铺 编辑:程序博客网 时间:2024/06/12 22:52
<!DOCTYPE html><html lang="en" ng-app="appService"><head>    <meta charset="UTF-8">    <title>测试directive</title>    <script src="frameWork/angular.js"></script>    <script src="frameWork/jquery-3.1.0.min.js"></script>    <script src="js/testService.js"></script></head><body><h3>用自带的$http直接读取</h3><div ng-controller="serviceCtrl">   <ul>       <li ng-repeat="u in users">名字:{{u.name}};年龄:{{u.age}}</li>   </ul></div><h3>自定义了封装$http服务,读取</h3><div ng-controller="customerServiceCtrl">    <input type="text" ng-model="username">    <ul>        <li ng-repeat="u in users">名字:{{u.name}};年龄:{{u.age}}</li>    </ul></div></body></html>
/** * Created by liyanq on 16/11/1. * 目的是练习service * * 1,$http * */var app = angular.module("appService", []);app.controller("serviceCtrl", function ($scope, $http) {    $http({        method: "GET",        url: "data/serviceData"    }).success(function (data, status, headers, config) {        $scope.users = data;    }).error(function (data, status, headers, config) {        console.log("error....");    });}).factory("myFirstService", function ($http) {    var doRequest = function (username, path) {        return $http({            method: "GET",            url: "data/serviceData"        })    };    return {        getUserList: function (username) {            return doRequest(username, "/path");        }    }}).controller("customerServiceCtrl", function ($scope, $timeout, myFirstService) {    var timeOut;    $scope.$watch("username", function (newUsername, oldUserName) {        console.log(newUsername + ";" + oldUserName);        if (newUsername) {            if (timeOut) {                console.log(timeOut);                $timeout.cancel(timeOut);            }        }        timeOut = $timeout(function () {            myFirstService.getUserList("userName")                .success(function (data, status, headers, config) {                    $scope.users = data;                }).error(function (data, status, headers, config) {                console.log("error....");            });        }, 300);    });});
没有过多练习,勉强写了些,以后实际用到的时候再练。
0 0
原创粉丝点击