1

I have service

angular.module('myapp')
.service('AnswerService', function() {
    var answers = [];
    this.addAnswers = function(questionId) { 
        answers.push(questionId);
        console.log(answers);
    }
    return this;
})

and have to retrieve the value of answers in controller and display it in html.

should I use return this or return answers?

5
  • 2
    What is the issue? Commented Jun 14, 2016 at 5:06
  • should that be 'return this' or 'return answers'? Commented Jun 14, 2016 at 5:07
  • i have called addAnswers func in my controller for looping and store the value in array. my issue is i have to retrieve 'answers' array in controller. Commented Jun 14, 2016 at 5:11
  • u can return answers Commented Jun 14, 2016 at 5:13
  • Depends on what you want to do... Do you want to expose the addAnswer functionality, or not? Commented Jun 14, 2016 at 6:25

4 Answers 4

2

Add another getter function, like,

angular.module('myapp')
.service('AnswerService', function() {
    var answers = [];
    this.addAnswers = function(questionId) { 
        answers.push(questionId);
        console.log(answers);
    }
    this.getAnswers = function() {
        return answers;
    }
});
Sign up to request clarification or add additional context in comments.

5 Comments

Exactly, beat me to it
how to call this in controller?
The same way you would have called 'addAnswers' function. Inject AnswerService to your controller, then do AnswerService.getAnswers();
it returns with empty array in ng-repeat
Please share your controller code as well in your question.
0

If you want to access array outside, it should be set to the service.

Add line

this.answers = answers;

angular.module('myapp')
.service('AnswerService', function() {

    var answers = [];
    this.addAnswers = function(questionId) { 
        answers.push(questionId);
        console.log(answers);
    }
    this.answers = answers;
    return this;
})

Comments

0
this.answers = answers;

I would return this

Comments

0

You should change your code to this.

angular.module('myapp').service('AnswerService', function() {
var answers = [];
this.addAnswers = function(questionId) { 
    answers.push(questionId);
    console.log(answers);
    return answers;
} })

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.