Anugular js 学习 service http

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27948659/article/details/79540837

Anugular js service学习

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $location) {
    $scope.myUrl = $location.absUrl();
});

通过location.absUrl() 获取当前网页url 地址
注意 $location 服务是作为一个参数传递到 controller中。如果要使用它,需要在 controller 中定义。

Anugular js 重点

标准格式


// 简单的 GET 请求,可以改为 POST
$http({
    method: 'GET',
    url: '/someUrl'
}).then(function successCallback(response) {
        // 请求成功执行代码
    }, function errorCallback(response) {
        // 请求失败执行代码
});

精简格式

$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
  • 使用菜鸟窝 json 进行网络get请求测试
http://www.runoob.com/try/angularjs/data/sites.php

{
    "sites": [
        {
            "Name": "菜鸟教程",
            "Url": "www.runoob.com",
            "Country": "CN"
        },
        {
            "Name": "Google",
            "Url": "www.google.com",
            "Country": "USA"
        },
        {
            "Name": "Facebook",
            "Url": "www.facebook.com",
            "Country": "USA"
        },
        {
            "Name": "微博",
            "Url": "www.weibo.com",
            "Country": "CN"
        }
    ]
}
  • 网页代码 (1.5版本以上 简要写法)

<div ng-app="myApp" ng-controller="siteCtrl"> 

<ul>
  <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('siteCtrl', function($scope, $http) {
  $http.get("http://www.runoob.com/try/angularjs/data/sites.php")
  .then(function (response) {$scope.names = response.data.sites;});
});
</script>

猜你喜欢

转载自blog.csdn.net/qq_27948659/article/details/79540837