码迷,mamicode.com
首页 > 其他好文 > 详细

Angular——自定义服务

时间:2018-02-08 17:44:14      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:factor   基本使用   text   his   style   back   char   filter   turn   

基本介绍

之前我们介绍了angular内置的几种服务,这里我们介绍如何自己定义自己的服务,主要是通过三个方法:factory、service、value

基本使用

factory:可以返回对象,也可以返回一个函数

<!DOCTYPE html>
<html lang="en" ng-app="App">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body ng-controller="DemoController">
<h1>{{now}}</h1>
<script src="../libs/angular.min.js"></script>
<script>
    var App = angular.module(App, []);
    App.factory(showTime, [$filter, function ($filter) {
        return function () {
            var now = new Date();
            return $filter(date)(now, yy-MM-dd);
        }
    }]);
    App.controller(DemoController, [$scope, showTime, function ($scope, showTime) {
        $scope.now = showTime();
    }]);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en" ng-app="App">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body ng-controller="DemoController">
<h1>{{now}}</h1>
<script src="../libs/angular.min.js"></script>
<script>
    var App = angular.module(App, []);
    App.factory(showTime, [$filter, function ($filter) {
        var now = new Date();
        return {
            now: $filter(date)(now, yy-MM-dd)
    }
    }]);
    App.controller(DemoController, [$scope, showTime, function ($scope, showTime) {
        $scope.now = showTime.now;
    }]);
</script>
</body>
</html>

service:和上面的factory有些区别,service里面可以用this追加属性和方法

<!DOCTYPE html>
<html lang="en" ng-app="App">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body ng-controller="DemoController">
<h1>{{now}}</h1>
<script src="../libs/angular.min.js"></script>
<script>
    var App = angular.module(App, []);
    App.service(showTime, [$filter, function ($filter) {
        var now = new Date();
        this.now = $filter(date)(now, yy-MM-dd);
    }]);
    App.controller(DemoController, [$scope, showTime, function ($scope, showTime) {
        $scope.now = showTime.now;
    }]);
</script>
</body>
</html>

value:类似于常量,和最开始初始化应用模块的ng-init十分相似,全局都可以访问

<!DOCTYPE html>
<html lang="en" ng-app="App">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body ng-controller="DemoController">
<h1>{{text}}</h1>
<script src="../libs/angular.min.js"></script>
<script>
    var App = angular.module(App, []);
    App.value(text, Hello World!);//定义一个常量,相当于ng-init
    App.controller(DemoController, [$scope, text, function ($scope, text) {
        $scope.text = text;
    }]);
</script>
</body>
</html>

 

Angular——自定义服务

标签:factor   基本使用   text   his   style   back   char   filter   turn   

原文地址:https://www.cnblogs.com/wuqiuxue/p/8432052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!