首页 > 技术文章 > angularJs 中controller与sever

scdisplay 2016-02-23 15:47 原文

网上找到的一个例子,感觉对于初学者理解将controller抽成服务有帮助。主要是方便理解什么时候应该来做服务。

html部分

<!DOCTYPE html>
<html ng-app="invoice1">
<head>
    <script src="../angular.min.js"></script>
    <script src="controllers.js"></script>
</head>
<body>
<div ng-controller="priceController as price">
    <b>订单:</b>
    <div>
        数量: <input type="number" ng-model="price.qty" required >
    </div>
    <div>
        单价: <input type="number" ng-model="price.cost" required >
        <select ng-model="price.inCurr">
            <option ng-repeat="c in price.currencies">{{c}}</option>
        </select>
    </div>
    <div>
        <b>总价:</b>
        <span ng-repeat="c in price.currencies">{{c}}{{price.total(c)|currency}}
        </span>
        <button class="btn" ng-click="price.pay()">支付</button>
    </div>
    <hr/>
    <p>控制器实例</p>
    <p>{{price}}</p>
</div>
</body>
</html>

主要是算总价:总价=单价*数量*不同货币汇率

angular.module('invoice1', [])
    .controller('priceController',function() {
        this.qty = 1;
        this.cost = 2;
        this.inCurr = 'EUR';
        this.currencies = ['USD', 'EUR', 'CNY'];
        this.usdToForeignRates = {
            USD: 1,
            EUR: 0.74,
            CNY: 6.09
        };

        this.convert=function(amount, inCurr, outCurr) {
            return amount * this.usdToForeignRates[outCurr] * 1 / this.usdToForeignRates[inCurr];
        };

        this.total = function total(outCurr) {
            return this.convert(this.qty * this.cost, this.inCurr, outCurr);
        };

        this.pay = function pay() {
            window.alert("谢谢!");
        };
    });

 

这个控制器内部可以分成2个部分,一部分是与视图相关的(单价,数量),一部分与视图无关的逻辑计算(计算公式)。因为单价,数量的变化会直接影响视图(结果),而计算公式是不变的,不直接影响视图即convert()函数。如果有多个控制器需要使用这个计算公式,就非常适合将其抽成服务来使用。

angular.module('invoice1', ["severModule"])
    .controller('priceController', ["mysever",function(mysever) {
        this.qty = 1;
        this.cost = 2;
        this.inCurr = 'EUR';
        this.currencies = mysever.currencies;

        this.total = function total(outCurr) {
            return mysever.convert(this.qty * this.cost, this.inCurr, outCurr);
        };

        this.pay = function pay() {
            window.alert("谢谢!");
        };
    }]);

简化后的控制器,同时注入了服务severModule,现在控制器只是处理了视图部分(计算了数量和单价的乘积),然后就是使用服务中的函数进行计算;

angular.module('severModule', [])
    .factory('mysever', function() {
        var currencies = ['USD', 'EUR', 'CNY'],
            usdToForeignRates = {
                USD: 1,
                EUR: 0.74,
                CNY: 6.09
            };
        return {
            currencies: currencies,
            convert: convert
        };

        function convert(amount, inCurr, outCurr) {
            return amount * usdToForeignRates[outCurr] * 1 / usdToForeignRates[inCurr];
        }
    });

服务内置了三种货币的汇率,根据指定的货币来计算其他货币的价格。提供一个对象(currencies和函数(convert)给控制器使用

 

推荐阅读