ng-repeat中的动态ng-model名
Dynamic ng-model names in an ng-repeat
我试图创建一个表单,允许在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的工作示例:
相关文章:
- 从 Javascript 中设置 ng-model name
- 在Angularjs中,我如何使用ng repeat、ng model和ng click来动态更改内容
- 如何在 AngularJS 中使用 ng-repeat 动态生成 ng-model=“my_{{$index}}”
- 在 AngularJS 中动态生成 ng-model
- AngularJS - 在带有重复和动态 html 控件的指令中使用 ng-model
- 无法在选择下拉菜单中使用动态生成下拉菜单ng-model设置默认选项
- 使用angularJS的ng-repeat和ng-model进行动态多列过滤
- 动态的ng-model变成ng-repeat AngularJS
- AngularJS -访问一个带有ng-model动态名称的输入数组
- 动态更改ng-bind和ng-model
- ng-repeat中的动态ng-model名
- 动态复选框不能与ng-model正确绑定
- AngularJS: ng-model动态绑定不起作用
- 用ng-model动态禁用一个span
- Angular js动态地指定ng-model,并返回该文本框的值
- 在AngularJS中动态设置ng-model value为js变量的值
- 使用 jquery 将 ng-model 动态添加到输入框属性
- Ng-model不支持动态添加的html控件
- 如何动态设置ng-model
- Angular ng-repeat with bootstrap输入复选框,动态ng-model使用ng-true-va