3

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 />
Rahul Sinha
  • 1,969
  • 14
  • 17
MukulSharma
  • 231
  • 2
  • 15

4 Answers4

2

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Thank u @dfsq ....i got my point of mistake. string.fn will not work. But if i don't concatenate or use like $scope.serviceResult = ServiceDemo and

    {{serviceResult.fn}}

    then it will work.
    – MukulSharma Jun 08 '16 at 13:08
  • If you don't concatenate and use `{{ serviceResult.fn }}` then it will work. – dfsq Jun 08 '16 at 13:20
0

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";
})
Karim
  • 8,454
  • 3
  • 25
  • 33
0

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

Tom Shen
  • 1,045
  • 3
  • 11
  • 29
0

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

Community
  • 1
  • 1
Amit Sirohiya
  • 333
  • 1
  • 13