[angularjs] angularjs系列笔记(五)Service

AngularJs中你可以使用自己的服务或使用内建服务,服务是一个函数或对象,以下代码试验$location服务,$http服务,$timeout服务,$intverval服务,创建自定义服务

 

 <body>
    <div ng-app="Home">
      <div ng-controller="Index">
        显示当前url
        <p>{{myUrl}}</p>
      </div>
      <div ng-controller="httpTest">
        展示http服务
        <p>{{myHttp}}</p>
      </div>
      <div ng-controller="timeoutTest">
        展示timeout服务
        <p>{{myName}}</p>
      </div>
      <div ng-controller="intervalTest">
        展示interval服务
        <p>{{myTime}}</p>
      </div>
      <div ng-controller="serviceTest">
        展示创建自定义Service
        <p>{{loginStatus}}</p>
      </div>
    </div>


  </body>

  <script type="text/javascript">
  //实例化应用对象,参数:模块名,空数组
  var app=angular.module("Home",[]);
  //调用Application对象的controller()方法
  app.controller("Index",function($scope,$location){
    $scope.myUrl=$location.absUrl();
  });
  //测试$http
  app.controller("httpTest",function($scope,$http){
    $http.get("index1.html").then(function(res){
      $scope.myHttp=res.data;
    });
  });
  //测试$timeout
  app.controller("timeoutTest",function($scope,$timeout){
    $scope.myName="taoshihan"
    $timeout(function(){
      $scope.myName="陶士涵"
    },2000);
  });
  //测试$interval
  app.controller("intervalTest",function($scope,$interval){
    $scope.myName="taoshihan"
    $interval(function(){
      $scope.myTime=new Date().toLocaleTimeString();
    },1000);
  });

  //测试自定义Service
  //调用Application对象的service()方法,参数:名称,匿名函数
  app.service("LoginService",function(){
    this.check=function(username,password){
      if(username=="1"&&password=="1"){
        return true;
      }else{
        return false;
      }
    }
  });
  app.controller("serviceTest",function($scope,LoginService){
    res=LoginService.check(1,1);
    if(res){
      $scope.loginStatus="登陆成功";
    }else{
      $scope.loginStatus="登陆失败";
    }
  });
  </script>

 

posted @ 2016-03-23 23:08  唯一客服系统开发笔记  阅读(211)  评论(0编辑  收藏  举报