MukulSharma
MukulSharma

Reputation: 221

Return value in angularjs service

I have two cases of using service return value in AngularJS.

Case 1. If I am using below code its working fine

var SerFactProv = angular.module("SerFactProv", [])
.service('ServiceDemo', function () {
    return { fn: "1452522" };
})
.controller("sfpCtrl", function ($scope, ServiceDemo, FactoryDemo, ProviderDemo) {
    $scope.serviceResult = "This is form service : " + ServiceDemo.fn
});

HTML:

<body ng-app="SerFactProv">
    <div ng-controller="sfpCtrl">
        <p>{{serviceResult}}</p>    <br />
    </div>
</body>

Case 2. But if I use .fn in angular expression in place of controller output disappears. Please see difference of .fn in both codes and explain why its happening.

$scope.serviceResult = "This is form service : " + ServiceDemo

and on UI

<p> {{serviceResult.fn}} </p>    <br />

Upvotes: 3

Views: 5351

Answers (4)

Karim
Karim

Reputation: 8632

just a tip, a service shouldn't be used to return an object, it's instantiated once by the core of angular and then cached so inside the service recipe you should refer with the keyword this as it is a constructor function:

 .service('ServiceDemo', function ()
{
   this.fn =  "1452522";
})

Upvotes: 0

Amit Sirohiya
Amit Sirohiya

Reputation: 333

If you want to return an object from angular service use 'factory' instead not service.

Factory:

.factory('ServiceDemo', function () {
    return { fn: "1452522" };
})

Controller :

.controller("sfpCtrl", function ($scope, ServiceDemo, FactoryDemo, ProviderDemo{
    $scope.serviceResult = "This is form service : " + ServiceDemo.fn
});

For difference between service, factory and providers see here

Upvotes: 0

Tom Shen
Tom Shen

Reputation: 1045

The reason your 2nd case doesn't work is because you've set the value of $scope.serviceResult as a string, and a string does not have a property .fn

If you set the $scope.serviceResult to serviceDemo (the service itself), it will work. I've used your code to make an example, this should explain the difference: jsFiddle

Upvotes: 0

dfsq
dfsq

Reputation: 193261

This code

$scope.serviceResult = "This is form service : " + ServiceDemo

and HTML:

<p> {{serviceResult.fn}} </p>

don't make any sense.

ServiceDemo is an object. Concatenation of the string and anything is going to be string too. Arbitrary string doens't have fn property. Hence the undefined result.

Upvotes: 2

Related Questions