Help us understand the problem. What is going on with this article?

Angular.jsのvalueとfactoryの違いを考える

More than 3 years have passed since last update.

次のようなHTMLがあったとする。

index.html
<!doctype html>
<html lang="jp" ng-app="App">
<head>
  <meta charset="utf-8">
  <script src="bower_components/angular/angular.js"></script>
  <script src="app.js"></script>
</head>
<body>
<div ng-controller="Ctrl">
  Value:{{answer}}
</div>
</body>
</html>

valueとfactoryの違いを考える

valueもfactoryもcontrollerから利用する値やfunctionを登録しておくのに使う。そのようなcontrollerの外部に登録されているfunction等をサービスと呼ぶ。たとえば、下記のようにplusminusといったサービスがあったとする。

app.js
angular.module('App',[])
  .value('plus', function(a,b){ return a+b; }) //plusサービス
  .value('minus', function(a,b){ return a-b; }) //minusサービス
  .controller('Ctrl',
    ["$scope", "plus", "minus",
      function($scope, plus, minus){
        $scope.answer = minus(plus(3,2),1); // 4
      }
    ]
  );

下記のように、plusminusを組み合わせたplus_minusというサービスを作りたいが、plus_minus内からplusminusは参照することができない。

app.js
angular.module('App',[])
  .value('plus', function(a,b){ return a+b; })
  .value('minus', function(a,b){ return a-b; })
  .value('plus_minus',function(a,b,c){
    return minus(plus(a,b),c); // minusやplusが参照できない
  })
  .controller('Ctrl',
    ["$scope", "plus_minus",
      function($scope, plus_minus){
        $scope.answerValue = plus_minus(3,2,1); // エラー
      }
    ]
  );

このように、登録されているサービスを利用するときにfactoryを使う。

app.js
angular.module('App',[])
  .value('plus', function(a,b){ return a+b; })
  .value('minus', function(a,b){ return a-b; })
  .factory('plus_minus', ["plus","minus",function(plus, minus){ // ここで明示的に参照
    return function(a,b,c){
      return minus(plus(a,b),c);
    };
  }])
  .controller('Ctrl',
    ["$scope", "plus_minus",
      function($scope, plus_minus){
        $scope.answer = plus_minus(3,2,1); // 4
      }
    ]
  );

次回はfactoryとserviceの違いを考える

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away