AngularJS 服务

AngularJS 服务

AngularJS 中可以创建自己的服务,或使用内建服务。

在 AngularJS 中,服务是一个函数或对象,可在AngularJS 应用中使用。

AngularJS 内建了30 多个服务。

$location 服务,返回当前页面的 URL 地址。

var app = angular.module('myApp', []);

app.controller('customersCtrl', function($scope, $location) {

    $scope.myUrl = $location.absUrl();

});

$http 向服务器发送请求,应用响应服务器传送过来的数据。

AngularJS 会一直监控应用,处理事件变化, AngularJS 使用 $location 服务比使用 window.location 对象更好。

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, $http) {

    $http.get("welcome.htm").then(function (response) {

        $scope.myWelcome = response.data;

    });

});

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

    <ul>

        <li ng-repeat="x in names">

            {{ x.Name + ', ' + x.Country }}

        </li>

    </ul>

</div>

<script>

    var app = angular.module('myApp', []);

    app.controller('customersCtrl', function($scope, $http) {

        $http.get("http://www.runoob.com/try/angularjs/data/Customers_JSON.php")

        .success(function(response) {$scope.names = response.records;});

    });

</script>

AngularJS $timeout 服务对应了 JS window.setTimeout 函数。

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, $timeout) {

    $scope.myHeader = "Hello World!";

    $timeout(function () {

        $scope.myHeader = "How are you today?";

    }, 2000);

});

AngularJS $interval 服务对应了 JS window.setInterval 函数。

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, $interval) {

    $scope.theTime = new Date().toLocaleTimeString();

    $interval(function () {

        $scope.theTime = new Date().toLocaleTimeString();

    }, 1000);

});

创建自定义服务

app.service('hexafy', function() {

    this.myFunc = function (x) {

        return x.toString(16);

    }

});

app.controller('myCtrl', function($scope, hexafy) {

    $scope.hex = hexafy.myFunc(255);

});

猜你喜欢

转载自mengxiang-it.iteye.com/blog/2321860