zoukankan      html  css  js  c++  java
  • 常用内置服务

    Angular 内置了很多服务,例如$location服务,用来和浏览器的地址栏进行交互;$root服务,用来根据URL地址的变换切换视图;还有$http服务,

    用来和服务器进行交互。
     $routeProvider

    使用 $routeProvider绑定路由与视图。

    我们可以利用路由服务定义这样一种东西:对于浏览器所指向的特定URL,Angular将会加载并显示一个模板,并实例化一个控制器来为模板提供内容




        

    //执行严格的js语法检查
    'use strict';


    angular
    //新建模块,应用名是cepWebApp,接着是依赖的模块。
      .module('cepWebApp', [
        'ngCookies',
        'ngResource',
        'ngSanitize',
        'ngRoute',
        'cepWebApp.configs',
        'ui.bootstrap',
        'toastr'
      ])
      //开始配置路由与对应的html模板视图
      .config(function ($routeProvider) {
        $routeProvider
          .when('/', {
            redirectTo: '/dataSource'
          })
          .when('/dataSource', {
            templateUrl: 'views/dataSource/dataSourceConfig.html',
            controller: 'DataSourceConfigCtrl'
          })
          .when('/counter', {
            templateUrl: 'views/counter/counter.html',
            controller: 'CounterCtrl'
          })
          .when('/rule', {
            templateUrl: 'views/rule/rule.html',
            controller: 'RuleCtrl'
          })
          .when('/statistics', {
            templateUrl: 'views/statistics/statistics.html',
            controller: 'StatisticsCtrl'
          })
          //不满足上面when时的情况
          .otherwise({
            redirectTo: '/'
          });
      })


    ;

    来自CODE的代码片
    app.js

    切换视图的原理:Angular发起下图的请求:


    XHR:SmlHttpRequest,本质是Ajax。

    注意URL的变化,是在'#'后面的,这个是HTML标准的页内标签,Angular通过这个标准实现了路由子页面这一自己的目的。


    $http
    $http.get(url) : get方式获取url返回。

    [html] view plain copy

        <!DOCTYPE html>  
        <html>  
        <body>  
          
        <div ng-app="" ng-controller="customersController">   
          
          
        <h3>  得到的JSON数据 </h3>  
        <br>  
        <table class="table table-striped">  
          <thead>  
            <tr>  
              <th>名</th>  
              <th>城市</th>  
              <th>国家</th>  
            </tr>  
          </thead>  
          <tbody>  
            <tr ng-repeat="x in names">  
          
              <td>{{ x.Name }}</td>  
         <td>{{ x.City}}</td>  
              <td>{{ x.Country }}</td>  
            </tr>  
          </tbody>  
        </table>  
          
        </div>  
          
        <script>  
        function customersController($scope,$http) {  
          $http.get("http://www.w3cschool.cc/try/angularjs/data/Customers_JSON.php")//这个http请求会拿到纯文本返回,里面是json内容。  
          .success(function(response) {$scope.names = response;});//response就是json格式的数据,相当于把json反序列化为了js对象。  
        }  
        </script>  
          
        <script src="http://apps.bdimg.com/libs/angular.js/1.2.15/angular.min.js"></script>  
          
        </body>  
        </html>  
                      

    $http拿到的json内容见下:

    [plain] view plain copy

        [ { "Name" : "Alfreds Futterkiste", "City" : "Berlin", "Country" : "Germany" }, { "Name" : "Berglunds snabbköp", "City" :

    "Luleå", "Country" : "Sweden" }, { "Name" : "Centro comercial Moctezuma", "City" : "México D.F.", "Country" : "Mexico" }, { "Name"

    : "Ernst Handel", "City" : "Graz", "Country" : "Austria" }, { "Name" : "FISSA Fabrica Inter. Salchichas S.A.", "City" : "Madrid",

    "Country" : "Spain" }, { "Name" : "Galería del gastrónomo", "City" : "Barcelona", "Country" : "Spain" }, { "Name" : "Island

    Trading", "City" : "Cowes", "Country" : "UK" }, { "Name" : "Königlich Essen", "City" : "Brandenburg", "Country" : "Germany" }, {

    "Name" : "Laughing Bacchus Wine Cellars", "City" : "Vancouver", "Country" : "Canada" }, { "Name" : "Magazzini Alimentari Riuniti",

    "City" : "Bergamo", "Country" : "Italy" }, { "Name" : "North/South", "City" : "London", "Country" : "UK" }, { "Name" : "Paris

    spécialités", "City" : "Paris", "Country" : "France" }, { "Name" : "Rattlesnake Canyon Grocery", "City" : "Albuquerque", "Country"

    : "USA" }, { "Name" : "Simons bistro", "City" : "København", "Country" : "Denmark" }, { "Name" : "The Big Cheese", "City" :

    "Portland", "Country" : "USA" }, { "Name" : "Vaffeljernet", "City" : "Århus", "Country" : "Denmark" }, { "Name" : "Wolski Zajazd",

    "City" : "Warszawa", "Country" : "Poland" } ]  

    网页效果

    $http.jsonp()
    用于get请求跨域访问获得json。
    原理见 http://blog.csdn.net/chuchus/article/details/44828313
    一个实例:
    [javascript] view plain copy

        $http.jsonp(  
            "http://115.28.88.165/ws/qing/timeSpan"+ "?callback=JSON_CALLBACK").success(  
            function(data) {  
                $scope.timeSpan = data;  
            }).error(function(data) {  
                console.log(data);  
        });  

    JSON_CALLBACK会被框架处理,如变成“angular.callbacks._0”。
    期望返回报文的Content-Type应该是application/x-javascript;内容应该是angular.callbacks._0({"name":"xiaoMing"}); 。这样的话,data就

    是框架处理后的json。
    $http.post()
    post方式发起http请求。此时请求的Content-Type默认为  application/json;charset=UTF-8 。
    [javascript] view plain copy

        var postData={"name":"xiaoHong","age":"13","book":{"name":"Physics"}};  
            $http.post("http://localhost:8080/WebService/student/post",postData).success(function(data) {  
                //$scope.receivedData = data;  
                console.log("hehe");  
                console.log(data);  
            }).error(function(data) {  
                console.log(data);  
            });  


    $http.get()与$http.post()都是有回调的,需要的时候可以加上。
    $interval(定时器)

    $interval(fn, delay, [count], [invokeApply]);
    说明: fn是函数,delay是定时器的间隔,单位是毫秒。count为可选参数,表明,执行多少次后停止。
    invokeApply:bool类型,If set to false skips model dirty checking, otherwise will invoke fn within the $apply block。
    $q与promise(异步执行结果)
    详见其他文章  http://my.oschina.net/ilivebox/blog/293771
    [javascript] view plain copy

        var deferred=$q.defer();  
        var promise=deferred.promise;//promise用来描述异步执行结果  
        if(/*成功执行*/){  
            deferred.resolve();//表示成功执行  
        }else{  
            deferred.reject();//没有成功执行  
        }  
        promise.then(/*do something*/);//成功执行后调用  
        promise.then(/*do other thing*/);//这是第二个then,执行失败后调用  
        /*也可以链式写promise.then(/*do something*/).then(/*do other thing*/);*/  

    解决多个ajax请求之间的依赖,除了用回调,还可以用promise。
    [javascript] view plain copy

        // 展示爬虫系统的下一个url并解析此url  
        $scope.nextDisplay = function() {  
            $scope.getNextUrl().then(function success(data) {  
                $scope.urlService($scope.nextUrl)  
            });  
        }  
        //拿到爬虫系统的下一个url                   
        $scope.getNextUrl = function() {  
            var promise = $http  
                    .get(  
                            "/GraduationProjectCollect/webService/spiderService/nextUrl")  
                    .success(function(data) {  
                        $scope.nextUrl = data;//我们的目的是 这一句执行后再执行$scope.urlService($scope.nextUrl)函数  
                    }).error(function(data) {  
                        alert("获取爬虫系统地nextUrl失败");  
                        console.log(data);  
                    });  
            return promise;  
        } 

  • 相关阅读:
    Quartz.Net 学习随手记之04 构建Windows Service承载服务
    Quartz.Net 学习随手记之03 配置文件
    SQL Server问题之计算机名称更改后无法登陆本地数据库
    SQL Server问题之The remote procedure call failed. [0x800706be]
    跨框架菜单menuG5使用
    DLink 524M经常断线、掉线问题的解决
    MSChart使用导航之开发
    ReSharper制作Template帮助我们快速输入代码
    网站右下角弹出通知效果的制作
    Dell6400拆卸与维护
  • 原文地址:https://www.cnblogs.com/huangshikun/p/7156910.html
Copyright © 2011-2022 走看看