0

I was trying a code to put a value in html page from angular js controller which is injected with a service.

I create an object in the service and add some value as property to this object. Next i read this value in the controller.

Now what i am observing is that the name of the service and name of the object should be same, only then the value is coming properly else not.

Following is the HTML code:-

<html>
  <head>
     <title>AngularJS Services</title>
     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
     <script type="text/javascript" src="abc.js"></script>
  </head>
  <body ng-app="myApp">
  <div ng-controller="Addition as add">
    <p>{{ add.num }}</p>
    </div>
  </body>
  </html>

Following is the working code:-

abc.js

angular.module('myApp',[]);
angular.module('myApp').factory('number',function(){
var number={};
number.val=10;
return number;
});

angular.module('myApp').controller('Addition',function(number){

var self=this;
self.num=number.val;
});

Following is the code which is not working:-

angular.module('myApp',[]);
angular.module('myApp').factory('number',function(){
var num={};
num.val=10;
return num;
});

angular.module('myApp').controller('Addition',function(number){

var self=this;
self.num=num.val;
});

Is is mandatory that service name and the object name should be same?

2 Answers 2

1

You made a small error. It should be:

angular.module('myApp').controller('Addition',function(number){

var self=this;
self.num=number.val;
});
Sign up to request clarification or add additional context in comments.

1 Comment

this is when i declare object with name number, which is working fine. But when i declare num it is not working. angular.module('myApp',[]); angular.module('myApp').factory('number',function(){ var num={}; num.val=10; return num; }); angular.module('myApp').controller('Addition',function(number){ var self=this; self.num=num.val; });
1

That's because num is undefined in your function

angular.module('myApp')
.controller('Addition',function( number ){

    var self=this;
        self.num = num.val;
});

All you are getting is a reference to num in your controller.

'number' is just the name of your factory. Hence, the above code will not work.

You'll have to use.

angular.module('myApp')
.controller('Addition',function(number){

    var self=this;
    self.num = number.val;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.