AngularJS进阶(四十)创建模块、服务_js html tri-buttoncounter(1)

<title>Angluar test</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
{{city}}
Total Clicks: {{data.totalClicks}}

angular.module(“exampleApp”, [])
.controller(“defaultCtrl”, function ($scope) {
// 数据模型
$scope.data = {
// 城市
cities : [“London”, “New York”, “Paris”],
// 点击总数
totalClicks : 0
};
// 添加监听器,当点击总数发生变化时触发工厂函数
s c o p e . scope. scope.watch(“data.totalClicks”, function (newVal) {
console.log("Total click count: " + newVal);
});
})
// 定义指令
.directive(“triButton”, function () {
return {
// 隔离作用域
// 双向数据绑定
scope : {
counter : “=counter”
},
// 链式函数
link : function (scope, element, attrs) {
// 点击事件监听,打印日记,计算累加
element.on(“click”, function (e) {
console.log("Button click: " + e.target.innerText);
scope.$apply(function () {
scope.counter++;
})
});
}
}
})

```

单击城市按钮,递增点击总数

接下来,我们将指令分离,使之模块化,我们命名为triButtonDirective.js

angular.module("triButtonDir", [])
    .directive("triButton", function () {
        return {
            // 隔离作用域
            // 双向数据绑定
            scope : {
                counter : "=counter"
            },
            // 链式函数
            link : function (scope, element, attrs) {
                // 点击事件监听,打印日记,计算累加
                element.on("click", function (e) {
                    console.log("Button click: " + e.target.innerText);
                    scope.$apply(function () {
                        scope.counter++;
                    })
                });
            }
        }
    })

接下来,引用定义的标签并且使用它

<!-- 引入指令文件 -->
<script type="text/javascript" src="js/triButtonDirective.js"></script>
<script type="text/javascript">
// 使用指令
angular.module("exampleApp", ["triButtonDir"])

二、创建使用服务

1.使用Factory方法

第一步:将服务模块化,这里创建一个名为triButtonFactory.js的文件

angular.module("triButtonFactory", [])
    .factory("logService", function () {
        var messageCount = 0;
        return {
            log : function (msg) {
                console.log("(Log + " + messageCount++ + ") " + msg);
            }
        }
    })

第二步:在视图中引入该服务

<script type="text/javascript" src="js/triButtonFactory.js"></script>

第三步:在控制器中使用它

// 参数依赖注入
angular.module("exampleApp", ["triButtonDirective", "triButtonFactory"])
    // 作为参数传人控制器中
    .controller("defaultCtrl", function ($scope, logService) {
        // 数据模型
        $scope.data = {
            // 城市
            cities : ["London", "New York", "Paris"],
            // 点击总数
            totalClicks : 0
        };
        // 添加监听器,当点击总数发生变化时触发工厂函数
        $scope.$watch("data.totalClicks", function (newVal) {
            // console.log("Total click count: " + newVal);
            // 使用自定义服务
            logService.log("Total click count: " + newVal);
        });
    })
<img data-cke-saved-src="https://img-blog.csdn.net/20160615210752345?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" src="https://img-blog.csdn.net/20160615210752345?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />


2.使用Service方法

第一步:创建构造函数,然后创建服务。我们命名为triButtonService.js

var baseLogger = function () {
    this.messageCount = 0;
    this.log = function (msg) {
        console.log(this.msgType + ": " + (this.messageCount++) + " " + msg);
    }
}
var debugLogger = function () {};
debugLogger.prototype = new baseLogger();
debugLogger.prototype.msgType = "Debug";
var errorLogger = function () {};
errorLogger.prototype = new baseLogger();
errorLogger.prototype.msgType = "Error";
angular.module("triButtonService", [])
    .service("logService", debugLogger)

第二步:引入triButtonService.js文件,然后使用服务

<!DOCTYPE>
<!-- use module -->
<html ng-app="exampleApp">
<head>
    <title>Angluar test</title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
</head>
<body ng-controller="defaultCtrl">
    <div class="well">
        <!-- 使用自定义指令 -->
        <div class="btn-group" tri-button counter="data.totalClicks">
            <!-- 遍历按钮 -->
            <button class="btn btn-default" ng-repeat="city in data.cities">
                {{city}}
            </button>
        </div>
        <h5>Total Clicks: {{data.totalClicks}}</h5>
    </div>
<script type="text/javascript" src="js/angular.min.js"></script>
<!-- 引入指令文件 -->
<script type="text/javascript" src="js/triButtonDirective.js"></script>
<script type="text/javascript" src="js/triButtonService.js"></script>
<script type="text/javascript">
// 使用指令
angular.module("exampleApp", ["triButtonDirective", "triButtonService"])
    .controller("defaultCtrl", function ($scope, logService) {
        // 数据模型
        $scope.data = {
            // 城市
            cities : ["London", "New York", "Paris"],
            // 点击总数
            totalClicks : 0
        };
        // 添加监听器,当点击总数发生变化时触发工厂函数
        $scope.$watch("data.totalClicks", function (newVal) {
            // console.log("Total click count: " + newVal);
            // 使用自定义服务
            logService.log("Total click count: " + newVal);
        });
    })
 </script>
</body>
</html>
<img data-cke-saved-src="https://img-blog.csdn.net/20160615210907926?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" src="https://img-blog.csdn.net/20160615210907926?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />


3.使用Provider方法

第一步:使用Provider,创建服务。我们命名为triButtonProvider.js

angular.module("triButtonProvider", [])
    .provider("logService", function () {
        var counter = true;
        var debug = true;
        return {
            messageCounterEnabled : function (setting) {
                if (angular.isDefined(setting)) {
                    counter = setting;
                    return this;
                } else {
                    return counter;
                }
            },
            debugEnabled : function (setting) {
                if (angular.isDefined(setting)) {
                    debug = setting;
                    return this;
                } else {
                    return debug;
                }
            },
            // 用于返回服务对象
            $get : function () {
                return {
                    messageCount : 0,
                    log : function (msg) {
                        if (debug) {
                            console.log("(LOG" + (counter ? " + " + this.messageCount++ + ") " : ") " + msg));
                        }
                    }
                }
            }
        }
    })

第二步:引入、配置和使用服务

<!DOCTYPE>
<!-- use module -->
<html ng-app="exampleApp">
<head>
    <title>Angluar test</title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
</head>
<body ng-controller="defaultCtrl">
    <div class="well">
        <!-- 使用自定义指令 -->
        <div class="btn-group" tri-button counter="data.totalClicks">
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值