2016-09-22 77 views
1

我正在學習angularjs並閱讀關於服務和工廠的文章。在ARTICLE上提供的一個示例是Service Fiddle如何在現有服務的角度創建工廠

在閱讀本文時,我試圖將服務轉換爲工廠,這是鏈接到My Factory Fiddle。但仍然沒有按預期工作,我不知道我做錯了什麼。

HTML

<div 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> 
    </div> 

JS

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

    app.factory('MathService', function() { 
    var myFactory = {}; 
     myFactory.add = function(a, b) { return a + b }; 

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

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

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

     retutn myFactory; 
    }); 

    app.factory('CalculatorService', function(MathService){ 
     var calcFactory = {}; 
     calcFactory.square = function(a) { return MathService.multiply(a,a); }; 
     calcFactory.cube = function(a) { return MathService.myFactory.multiply(a, MathService.myFactory.multiply(a,a)); }; 

     return calcFactory; 

    }); 

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

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

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

回答

2

出於某種原因,你撥弄抱怨說,它無法實例化 '應用程序' 模塊,所以一切都將失敗。

無論如何,這裏是一個小提琴的工作示例:https://jsfiddle.net/gom2q6bz/1/

請注意,您不需要撥打CalculatorService.calcFactory.cube,而是撥打CalculatorService.cube;

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

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

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

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

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

    return service; 
}); 

app.factory('CalculatorService', function(MathService) { 
    var service = {}; 
    service.square = function(a) { 
    return MathService.multiply(a, a); 
    }; 
    service.cube = function(a) { 
    return MathService.multiply(a, MathService.multiply(a, a)); 
    }; 

    return service; 

}); 

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

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

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