Snorlax
Snorlax

Reputation: 4765

AngularJS: passing in variables into a service

I created a service that has a method that does a simple calculation. It takes a value and squares it. However, I'm getting an error saying that square is undefined so I'm guessing I'm passing in the value incorrectly.

jsfid: http://jsfiddle.net/ADukg/19107/

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

/* function MyCtrl($scope) {
    $scope.name = 'Superhero';
} */

myApp.controller('MyCtrl', ['$scope', function($scope, CalcService) {
var cheese = CalcService.square(2);
  $scope.value = cheese;
  
}]);

myApp.service('CalcService', function(x){
   this.square = function(x) {

   var y = x*x;
      return y;
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MyCtrl">
  Hello, {{value}}!
</div>

Upvotes: 0

Views: 78

Answers (4)

Snehal S
Snehal S

Reputation: 34

You missed to inject 'CalcService'.

myApp.controller('MyCtrl', ['$scope','CalcService', function($scope, CalcService) { }]);

Upvotes: 1

Hanif
Hanif

Reputation: 3795

See here you missed CalcService inject in controller initialization:

myApp.controller('MyCtrl', ['$scope', 'CalcService', function($scope, CalcService) {
var cheese = CalcService.square(2);
$scope.value = cheese;

}]);

Upvotes: 1

Sergey Bogdanov
Sergey Bogdanov

Reputation: 1

Your service should be something like:

myApp.service('CalcService', function(){
return {
    square: function (x) {
        var y = x*x;
        return y;
    }
}});

And you should inject service in your controller.

Upvotes: 0

Arun
Arun

Reputation: 460

i think you missed to inject service to controller in proper way check the snippet

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>

  <div ng-app="myApp">

  <div ng-controller="MyCtrl">
  Hello, {{value}}!
</div>
  </div>
</body>

</html>

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

/* function MyCtrl($scope) {
    $scope.name = 'Superhero';
} */

myApp.service('CalcService', function(){
   this.square = function(x) {

   var y = x*x;
      return y;
   }
});
myApp.controller('MyCtrl', ['$scope','CalcService', function($scope, CalcService) {
var cheese = CalcService.square(2);
  $scope.value = cheese;
  
}]);


</script>

</body>

</html>

Upvotes: 1

Related Questions