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

<!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);
    });
});
没有过多练习,勉强写了些,以后实际用到的时候再练。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值