我正在尝试创建一个表单,允许将具有姓名和年龄字段的人员对象附加到 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);
};
}
然后在 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 issue (现在挂了 7 个月)。我不得不稍微修复一下 Angular 让它工作。我回答了similar question在那里你可以阅读一些细节。还有一个 working example with fixed Angular .
关于javascript - ng-repeat 中的动态 ng-model 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16263622/