如何在AngularJS中设置动态模型名称?

Mik*_*ras 88 angularjs

我想填写一个带有一些动态问题的表格(在这里小提琴):

<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}}"]);
    };
}?
Run Code Online (Sandbox Code Playgroud)

一切正常,除了模型实际上是Answers ["{{question.Name}}"],而不是评估的Answers ["GenderQuestion"].如何动态设置模型名称?

Tos*_*osh 119

http://jsfiddle.net/DrQ77/

你可以简单地把javascript表达式放入ng-model.


Wil*_*ckl 31

你可以使用这样的东西scopeValue[field],但是如果你的字段在另一个对象中,你将需要另一个解决方案.

要解决所有类型的情况,您可以使用此指令:

this.app.directive('dynamicModel', ['$compile', '$parse', function ($compile, $parse) {
    return {
        restrict: 'A',
        terminal: true,
        priority: 100000,
        link: function (scope, elem) {
            var name = $parse(elem.attr('dynamic-model'))(scope);
            elem.removeAttr('dynamic-model');
            elem.attr('ng-model', name);
            $compile(elem)(scope);
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

Html示例:

<input dynamic-model="'scopeValue.' + field" type="text">
Run Code Online (Sandbox Code Playgroud)

  • 救了我的一天:) (3认同)
  • 尼斯.但是仍然希望我们可以使用`ng-model ="{{variable}}"`:) (2认同)

abo*_*get 12

我最终做的是这样的:

在控制器中:

link: function($scope, $element, $attr) {
  $scope.scope = $scope;  // or $scope.$parent, as needed
  $scope.field = $attr.field = '_suffix';
  $scope.subfield = $attr.sub_node;
  ...
Run Code Online (Sandbox Code Playgroud)

所以在模板中我可以使用完全动态的名称,而不仅仅是在某个硬编码元素下(比如在你的"答案"案例中):

<textarea ng-model="scope[field][subfield]"></textarea>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.