Difference between service and factory

This question already has an answer here:

  • AngularJS: Service vs provider vs factory 30 answers

  • Both are singleton
  • They differ in terms of writing pattern
  • My personnel choice is to use service

  • 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);
                        }
    
                    }]);
    

    这是答案感谢支持

    链接地址: http://www.djcxy.com/p/13612.html

    上一篇: angularjs服务,供应商和工厂?

    下一篇: 服务和工厂的区别