-2

I am looking for any constructor type of function in Angular. I have created a service but it is giving me an error. Please help to accomplish the task.

My error code:

var app = angular.module("app1", [])

.service('NumberService', function (a) {
    this.square = function () { return a * a; };
    this.cube = function () { return a * a * a; };
})

.controller('ServiceController', ['$scope', 'NumberService',
    function ($scope, NumberService) {
        $scope.getData = function () {
            //  alert('Button clicked' );
            var n = $scope.a;
            var ns = new NumberService(n);
            $scope.Square = ns.square();
            // alert($scope.Square);
            $scope.Cube = ns.cube();
        }
    }
]);

I want to create NumberService as Singleton class. In c++/java/c#:

class NumberService
{
    int a;
    public NumberService(int n){ a=n;}
    public int square(){ return a*a;}
    public in cube(){ return a*a*a;}
}
Manfred Radlwimmer
  • 12,469
  • 13
  • 47
  • 56

1 Answers1

0

when you create something with .service() it becomes a singleton. You really shouldnt do:

var ns = new NumberService(n);

cause it NumberService points to a singleton instance already. So just do:

NumberService.square(2)

Why do you want it to be a singleton though, you math operations are cleary utility methods, no need for a state?

Chris Noring
  • 481
  • 3
  • 9
  • It means it becomes static class as we access method name with class name not instance name – GAURAV MAHAJAN Apr 09 '17 at 18:06
  • which is what it will become now with .service() If you want it to become an instance I would suggest looking at .factory(). So do you want a singleton or instance? Happy to amend by answer with a .factory + instance solution if that is what you need? – Chris Noring Apr 09 '17 at 18:08