ng 自定义服务

 

服务的本质是对象。

创建服务的常见方式:
factory(返回对象) service (方法、属性)constant(常量服务) value(变量服务)


1、factory
app.factory('服务名称',function(){
return {
key:value
}
})

2、service方法
app.service('服务名称',function(){
//构造函数
this.name = 'zhangsan';
this.speak = function(){}

})

3、constant value
app.constant('服务名称',{})
app.value('服务名称',{})

 

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
  <meta charset="UTF-8">
  <script src="js/angular.js"></script>
  <title></title>
</head>
<body>
<div ng-controller="myCtrl">
    <button ng-click="handleClick()">
      clickMe
    </button>
</div>
<script>
  var app = angular.module('myApp', ['ng']);

  //通过factory自定义服务
  app.factory('$output', function () {
    return {
      print: function (str) {
        //比较复杂的业务逻辑
        console.log(str);
      }
    }
  });

  app.controller('myCtrl',
    function ($scope,$output) {
      $scope.handleClick = function () {
        $output.print('Hello Service');
      }
    })
</script>
</body>
</html>

 

2.

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
  <meta charset="UTF-8">
  <script src="js/angular.js"></script>
  <title></title>
</head>
<body>
<div ng-controller="myCtrl">

</div>
<script>
  var app = angular.module('myApp', ['ng']);

  //通过service方法创建服务
  app.service('$student', function () {
    //构造函数
    this.name = 'lucy';
    this.study = function () {
      console.log('正在学习');
    }
  });

  app.controller('myCtrl',
    function ($scope,$student) {
      //读取服务中的属性
      console.log("服务中name属性对应的值为"+$student.name);
      //调用服务中的方法
      $student.study();
    })
</script>
</body>
</html>

 

转载于:https://www.cnblogs.com/web-fusheng/p/6958954.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值