How can I set a dynamic model name in AngularJS?

angularjs

Solution

http://jsfiddle.net/DrQ77/

You can simply put javascript expression in `ng-model`.

Problem

I want to populate a form with some dynamic questions (fiddle here): ``` <div ng-app ng-controller="QuestionController"> <ul ng-repeat="question in Questions"> <li> <div>{{question.Text}}</div> <select ng-model="Answers['{{question.Name}}']" ng-options="option for option in question.Options"> </select> </li> </ul> <a ng-click="ShowAnswers()">Submit</a> </div> ​ function QuestionController($scope) { $scope.Answers = {}; $scope.Questions = [ { "Text": "Gender?", "Name": "GenderQuestion", "Options": ["Male", "Female"]}, { "Text": "Favorite color?", "Name": "ColorQuestion", "Options": ["Red", "Blue", "Green"]} ]; $scope.ShowAnswers = function() { alert($scope.Answers["GenderQuestion"]); alert($scope.Answers["{{question.Name}}"]); }; }​ ``` Everything works, except the model is literally Answers["{{question.Name}}"], instead of the evaluated Answers["GenderQuestion"]. How can I set that model name dynamically?

Original source