Abhishek
Abhishek

Reputation: 351

How can we use service just like a factory?

<!DOCTYPE html>
<html ng-app='myApp'>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script>
    var app = angular.module('myApp', []);
    app.controller('x', function (ser) {
        alert(ser.val);
    });
    app.service('ser', function () {
        var obj = {};
        obj.val = 'xyz';
        return obj;
    })
</script>

<body>

    <h1 ng-controller='x'>My First JavaScript Animation</h1>

</body>

</html>

We can create on object and give the object properties and return it in factories,but service is a constructor function,but here in the program i'm doing the same as i should do in factory by creating and returning an object. Isn't it should be done using this keyword...but it's working.how?

Upvotes: 2

Views: 78

Answers (1)

Kalyan
Kalyan

Reputation: 1200

I referred this link: [https://www.airpair.com/angularjs/posts/top-10-mistakes-angularjs-developers-make][1]

As per that link:

These names cause confusion for almost every AngularJS developer when starting out. They really shouldn't because they're syntactic sugar for (almost) the same thing! Here are their definitions from the AngularJS source:

function factory(name, factoryFn) { 
    return provider(name, { $get: factoryFn }); 
}

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
      return $injector.instantiate(constructor);
    }]);
}

From the source you can see that service just calls the factory function which in turn calls the provider function.

Upvotes: 3

Related Questions