1

I want to be able to preserve scope data between route changes, so I created a service to return saved data to a controller for it to initiate on scope.

app.factory('answerService', function () {
    var answers = {
        1 : { text : "first answer" },
        2 : { text : "second answer" }
    }
    return {
        getAllAnswers: function () {
            return answers;
        },
        getFirstAnswer: function () {
            return answers[1];
        }
    }
});

In my controller, I initiate the first answer by calling the service to get the first answer.

app.controller('myController', function ($scope, answerService) {
    $scope.firstAnswer = answerService.getFirstAnswer();    
    $scope.answers = answerService.getAllAnswers();
});

http://jsfiddle.net/hientc/gj5knrg7/2/

The problem I'm having is that $scope.firstAnswer is somehow also being binded to $scope.answers. I don't want that, I only want the input to bind to scope.firstAnswer.text

What am I doing wrong?

1 Answer 1

1

This is because answers[1] is an object reference, and assigning its value to another variable signifies that the variable is a reference to that object. In order to get a copy of that value you can copy it using angular.copy().

Simply change getFirstAnswer() function to something like this:

DEMO

getFirstAnswer: function () {
  return angular.copy(answers[1]);
}
Sign up to request clarification or add additional context in comments.

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.