Can I set a dynamic model name?

6,138 views
Skip to first unread message

Michael Pateras

unread,
Sep 23, 2012, 11:36:25 AM9/23/12
to ang...@googlegroups.com

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?

Peter Bacon Darwin

unread,
Sep 23, 2012, 11:50:27 AM9/23/12
to ang...@googlegroups.com
I would suggest that the best thing to do is have a controller on the UL or LI and get that controller to create a field on its scope called answer, like so:


<div ng-app ng-controller="QuestionController">
    <ul ng-repeat="question in Questions" ng-controller="AnswerController">
        <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 AnswerController($scope) {
   $scope.answer = $scope.Answers[$scope.question.Name];

--
You received this message because you are subscribed to the Google Groups "AngularJS" group.
To post to this group, send email to ang...@googlegroups.com.
To unsubscribe from this group, send email to angular+u...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular?hl=en.
 
 

Michael Pateras

unread,
Sep 24, 2012, 3:47:02 PM9/24/12
to ang...@googlegroups.com
Two answers here:  http://stackoverflow.com/questions/12553617/how-can-i-set-a-dynamic-model-name-in-angularjs

I went with mine, but verified the accepted answer.

On Sun, Sep 23, 2012 at 12:08 PM, Michael Pateras <pat...@gmail.com> wrote:
Could you update the fiddle? I'm not quite sure I understand what you're suggesting.
Reply all
Reply to author
Forward
0 new messages