zoukankan      html  css  js  c++  java
  • 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);

    });

  • 相关阅读:
    绝对路径和相对路径的问题
    get请求中的中文乱码问题的解决方法
    jsp中的另一种分页实现方法
    jsp中退出功能实现代码
    jsp中完整的分页显示和页面跳转功能实现的源代码
    jsp中未登录用户也可以浏览页面的功能实现代码
    date和calendar对象的转化,使用,以及插入数据库中的总结
    jsp中向数据库中插入当前时间的方法精确到秒
    硬盘方式安装 Windows 7
    HP笔记本中CQ4x系列,在XP下的未知设备与声卡设备驱动
  • 原文地址:https://www.cnblogs.com/DreamFather/p/11326892.html
Copyright © 2011-2022 走看看