服务和工厂之间的区别

时间:2017-02-21 09:22:47

标签: angularjs

我们如何将代码转换/更改为工厂而非服务

在这两个工厂和服务中实施的更好方法是什么,请建议。 我是AngularJs的新手,所以请帮助我解决这个问题

<html>

    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

    </head>

<body ng-app="app">


    <div ng-controller="CalculatorController">
        Enter a number:
        <input type="number" ng-model="number" />
        <button ng-click="doSquare()">X<sup>2</sup></button>
        <button ng-click="doCube()">X<sup>3</sup></button>

        <div>Answer: {{answer}}</div>
    </div>



    <script>

        var app = angular.module('app', []);

            app.service('MathService', function() {
                this.add = function(a, b) { return a + b };

                this.subtract = function(a, b) { return a - b };

                this.multiply = function(a, b) { return a * b };

                this.divide = function(a, b) { return a / b };
            });

            app.service('CalculatorService', function(MathService){

                this.square = function(a) { return MathService.multiply(a,a); };
                this.cube = function(a) { return MathService.multiply(a, MathService.multiply(a,a)); };

            });

            app.controller('CalculatorController', function($scope, CalculatorService) {

                $scope.doSquare = function() {
                    $scope.answer = CalculatorService.square($scope.number);
                }

                $scope.doCube = function() {
                    $scope.answer = CalculatorService.cube($scope.number);
                }
            });

    </script>

</body>
</html>

2 个答案:

答案 0 :(得分:3)

  • 两者都是单身人士
  • 他们在写作模式方面有所不同
  • 我的人员选择是使用服务

答案 1 :(得分:0)

var app = angular.module('app', []);
                app.factory('MathService', function(){
                    return {
                        multiply : function(a, b){
                            return a*b;
                        }
                    }
                });

                app.factory('CalculateResult', ['MathService', function(MathService){
                        return {
                            square : function(a){
                                return MathService.multiply(a,a);
                            },

                            cube : function(a){
                                return MathService.multiply(a, MathService.multiply(a,a));
                            }
                        }
                }]);

                app.controller('CalculatorController', ['CalculateResult', '$scope', function(CalculateResult, $scope){

                    $scope.doSquare = function(){
                        $scope.answer = CalculateResult.square($scope.number);
                    };

                    $scope.doCube = function(){
                        $scope.answer = CalculateResult.cube($scope.number);
                    }

                }]);

这是答案感谢支持

相关问题