ng-repeat中的动态ng-model名

Dynamic ng-model names in an ng-repeat

本文关键字:ng-model 动态 ng-repeat      更新时间:2023-09-26

我试图创建一个表单,允许在Angularjs中添加一个具有姓名和年龄字段的人对象,但我无法获得字段名称来正确渲染。下面是不起作用的代码:

  %tr
    %td{ 'ng-repeat' => 'h in maintitles' }
      %input{ :type => 'text', :value => '{{h.name}}', 'ng-model' => 'newPerson.' + '{{h.name}}' }
    %td
      %button{ 'ng-click' => 'addItem(newItem)' } Add

(haml确实编译正确-每个输入字段都有newPerson.{{h.name}}ng-model属性,value字段正确呈现为{{h.name}}的值,而不是文本"{{h.name}}"-所以问题肯定是在javascript中。)

如果我手动命名每个字段,例如:

  %tr
    %td{ 'ng-repeat' => 'h in maintitles' }
      %input{ :type => 'text', :value => '{{h.name}}', 'ng-model' => 'newPerson.name' }
    %td{ 'ng-repeat' => 'h in maintitles' }
      %input{ :type => 'text', :value => '{{h.name}}', 'ng-model' => 'newPerson.age' }
    %td
      %button{ 'ng-click' => 'addItem(newItem)' } Add

那么一切都按预期进行。

我如何让Angular允许我在ng-model指令中使用变量?


编辑:根据Yaroslav的回答,我通过创建maintitles数组的克隆来解决这个问题,其中包含一个空数据字段来保存新值:

function AdminItemCtrl($scope, $http, $routeParams) {
    $scope.titlename = $routeParams.itemType;
    $http.get('/data/' + $scope.titlename + 'items.json').success(function(data) {
        $scope.maintitles = data.titles;
        $scope.main = data.data;
        $scope.emptyItem = angular.copy($scope.maintitles);
        for (var i = 0; i < $scope.emptyItem.length; i++) {
            delete $scope.emptyItem[i].editable;
            $scope.emptyItem[i].data = '';
        }
        $scope.cleanEmpty = angular.copy($scope.emptyItem);
    });
    $scope.addItem = function(newItem) {
        var newObject = {};
        for (var i = 0; i < newItem.length; i++)
            newObject[newItem[i].name] = newItem[i].data;
        $scope.main.push(newObject);
        $scope.emptyItem = angular.copy($scope.cleanEmpty);
    };
}

then在HAML中:

  %tr
    %td{ 'ng-repeat' => 'h in emptyItem' }
      %input{ :type => 'text', :placeholder => '{{h.name}}', 'ng-model' => 'h.data' }
    %td
      %button{ 'ng-click' => 'addItem(emptyItem)' } Add

简而言之,Angular不支持这个。NgModelController在插入之前获得了它的名称,因此在错误的名称下发布。有一个开放的github问题(挂了7个月了)。为了让它正常工作,我不得不对Angular做了一些修改。我回答了一个类似的问题,你可以在这里阅读一些细节。还有一个固定Angular的工作示例: