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?
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:
getFirstAnswer: function () {
return angular.copy(answers[1]);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments