angular-get ng-model name from scope var

时间:2014-11-29 18:34:14

标签: javascript angularjs

有什么方法可以做到吗?

  ng-model="{{att.myModel}}"

我有一个名为AllSmallText的数组,带有项目。我想在AllSmallText上使用ng-repeat构建表单,并将ng-model值设置为myModel,这是项目字段之一。

   <div ng-repeat="att in AllSmallText" class="col-xs-6 col-md-6">
           <input class="form-control" name="firstname" placeholder="{{att.title}}"  type="text"
              ng-model="{{att.myModel}}"
              required autofocus />
   </div>

感谢

3 个答案:

答案 0 :(得分:2)

您不需要大括号,请使用ng-model='attr.myModel'

更新了答案

ngModel将尝试通过评估当前范围上的表达式绑定到给定的属性。 如果该范围上尚不存在该属性,则将隐式创建该属性并将其添加到范围中。

添加新范围

$scope.myForm = {};

使用ng-model="myForm[attr.myModel]",这将创建一个新的范围属性,如$scope.myForm.hello

希望这有帮助。

答案 1 :(得分:1)

如果有人以这种方式寻找任何内容,您可以使用以下语法:

代替ng-model =&#34; {{att.myModel}}&#34;使用ng-model =&#34; [att.myModel]&#34;

答案 2 :(得分:0)

有一种方法可以接近它,即通过另一个指令添加ng-model指令。

您可以在标记中添加一个add-model指令:

<input type="text" add-model="{{myModel}}" />

然后在指令中添加ng-model:

myApp.directive('addModel', function($compile) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs, ctrl) {
            var model = attrs.addModel;
            element.attr('ng-model',  model);
            element.removeAttr('add-model');  // avoid infinite loop
            $compile(element)(scope);
        }
    };
});

小提琴:http://jsfiddle.net/oligustafsson/wuqqxtqu/