dellboyant
dellboyant

Reputation: 27

Issue with angular factory service

I'm trying to get my head round Angular services. I've created a simple example but when I try to utilize the service the console spits out an error (see below)

app.js

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

service.js

myApp.factory('Addition', function() {
  return {
    plusOne: function() {
      $scope.number += 1;
    }
  };
})

UserController.js

myApp.controller( 'UserCtrl', [ '$scope', 'Addition', function($scope, Addition ) {

  $scope.number = 0;

  $scope.plusOne = Addition.plusOne();

}]);

view.html

<div ng-controller="UserCtrl">
     {{number}}

  <button ng-click=plusOne()></button>

</div>

The view displays $scope.number correctly until I add $scope.plusOne = Addition.plusOne(); and the console spits out

ReferenceError: $scope is not defined at Object.plusOne

I'm probably missing something fairly fundamental here but would really appreciate any help.

Upvotes: 1

Views: 51

Answers (2)

Sathya
Sathya

Reputation: 233

Better to do like this. Because "{{getPlusOneValue()}}" function will be fired in all angular digest cycle which we don't need.

Markup

<div ng-controller="UserCtrl" ng-bind="number">
  <button ng-click=plusOne()></button>
</div>

Factory

myApp.factory('Addition', function() {
  var number = 0;
  return {
    //plus one getter
    getPlusOneValue: function(){
       return ++number;
    }
  };
})

Controller

myApp.controller( 'UserCtrl', [ '$scope', 'Addition', 
   function($scope, Addition ) {
      $scope.number = '';
      $scope.plusOne = function () {
        $scope.number = Addition.getPlusOneValue();
      }
   }
]);

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

You can not inject $scope dependency inside service, service/factory are singleton object which are there to share data between component of angular module.

Do change the implementation to below would work for you.

Markup

<div ng-controller="UserCtrl">
     {{getPlusOneValue()}}
  <button ng-click=plusOne()></button>
</div>

Code

myApp.factory('Addition', function() {
  var number = 0;
  return {
    plusOne: function() {
      number += 1;
    },
    //plus one getter
    getPlusOneValue: function(){
       return number;
    }
  };
})

Controller

myApp.controller( 'UserCtrl', [ '$scope', 'Addition', 
   function($scope, Addition ) {
      $scope.plusOne = Addition.plusOne;
      $scope.getPlusOneValue = Addition.getPlusOneValue;
   }
]);

Upvotes: 3

Related Questions