Javascript 动态分配 ng-model
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14183614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically assign ng-model
提问by George Ananda Eman
I'm trying to generate a set of check-boxes from an object array. I'm aiming to have the check-boxes dynamically map their ng-model to a property of the new object that will be submitted into the array.
我正在尝试从对象数组生成一组复选框。我的目标是让复选框将它们的 ng-model 动态映射到将提交到数组中的新对象的属性。
What I had in mind is something like
我想到的是
<li ng-repeat="item in items">
<label>{{item.name}}</label>
<input type="checkbox" ng-model="newObject.{{item.name}}">
</li>
This doesn't work as can be seen on this JSFiddle:
正如在这个 JSFiddle 上看到的那样,这不起作用:
http://jsfiddle.net/GreenGeorge/NKjXB/2/
http://jsfiddle.net/GreenGeorge/NKjXB/2/
Can anybody help?
有人可以帮忙吗?
回答by pkozlowski.opensource
This should give you desired results:
这应该会给你想要的结果:
<input type="checkbox" ng-model="newObject[item.name]">
Here is a working plunk: http://plnkr.co/edit/ALHQtkjiUDzZVtTfLIOR?p=preview
这是一个有效的 plunk:http://plnkr.co/edit/ALHQtkjiUDzZVtTfLIOR? p=preview
回答by Justus Wingert
EDITAs correctly noted in the comments using this with ng-change requires a "dummy" ng-model to be present beforehand. It should however be noted that apparently with 1.3 the required options have been provided by the framework. Please check out https://stackoverflow.com/a/28365515/3497830below! /EDIT
编辑正如评论中正确指出的那样,将其与 ng-change 一起使用需要预先存在“虚拟”ng-model。然而,应该注意的是,显然在 1.3 中,框架已经提供了所需的选项。请查看下面的https://stackoverflow.com/a/28365515/3497830! /编辑
Just in case you are like me stumbling over a simple case while having a more complex task, this is the solution I came up with for dynamically binding arbitrary expressions to ng-model: http://plnkr.co/edit/ccdJTm0zBnqjntEQfAfx?p=preview
以防万一你像我一样在一个更复杂的任务上绊倒一个简单的案例,这是我想出的将任意表达式动态绑定到 ng-model 的解决方案:http: //plnkr.co/edit/ccdJTm0zBnqjntEQfAfx?p =预览
Method: I created a directive dynamicModel that takes a standard angular expression, evaluates it and links the result to the scope via ng-model and $compile.
方法:我创建了一个指令 dynamicModel,它接受一个标准的角度表达式,评估它并通过 ng-model 和 $compile 将结果链接到范围。
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {};
$scope.testvalue = 'data.foo';
$scope.eval = $scope.$eval;
});
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {};
$scope.testvalue = 'data.foo';
$scope.eval = $scope.$eval;
});
app.directive('dynamicModel', ['$compile', function ($compile) {
return {
'link': function(scope, element, attrs) {
scope.$watch(attrs.dynamicModel, function(dynamicModel) {
if (attrs.ngModel == dynamicModel || !dynamicModel) return;
element.attr('ng-model', dynamicModel);
if (dynamicModel == '') {
element.removeAttr('ng-model');
}
// Unbind all previous event handlers, this is
// necessary to remove previously linked models.
element.unbind();
$compile(element)(scope);
});
}
};
}]);
Usage is simply dynamic-model="angularExpression" where angularExpression results in a string that is used as the expression for ng-model.
用法只是 dynamic-model="angularExpression",其中 angularExpression 产生一个字符串,用作 ng-model 的表达式。
I hope this saves someone the headache of having to come up with this solution.
我希望这可以避免有人不得不提出这个解决方案的麻烦。
Regards, Justus
问候,贾斯图斯
回答by Rob R
With Angular 1.3, you can use ng-model-optionsdirective to dynamically assign the model, or bind to an expression.
使用 Angular 1.3,您可以使用ng-model-options指令动态分配模型,或绑定到表达式。
Here is a plunkr: http://plnkr.co/edit/65EBiySUc1iWCWG6Ov98?p=preview
这是一个 plunkr:http://plnkr.co/edit/65EBiySUc1iWCWG6Ov98?p=preview
<input type="text" ng-model="name"><br>
<input type="text" ng-model="user.name"
ng-model-options="{ getterSetter: true }">
More info on ngModelOptionshere: https://docs.angularjs.org/api/ng/directive/ngModelOptions
更多信息ngModelOptions:https: //docs.angularjs.org/api/ng/directive/ngModelOptions
回答by Kanit Mekritthikrai
This is my approach to support deeper expression, e.g. 'model.level1.level2.value'
这是我支持更深层次表达的方法,例如'model.level1.level2.value'
<input class="form-control" ng-model="Utility.safePath(model, item.modelPath).value">
where item.modelPath = 'level1.level2' and Utility(model, 'level1.level2') is the utility function that returns model.level1.level2
其中 item.modelPath = 'level1.level2' 和 Utility(model, 'level1.level2') 是返回 model.level1.level2 的效用函数
回答by Arun Kumar Saini
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form name="priceForm" ng-submit="submitPriceForm()">
<div ng-repeat="x in [].constructor(9) track by $index">
<label>
Person {{$index+1}} <span class="warning-text">*</span>
</label>
<input type="number" class="form-control" name="person{{$index+1}}" ng-model="price['person'+($index+1)]" />
</div>
<button>Save</button>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.price = [];
$scope.submitPriceForm = function () {
//objects be like $scope.price=[{person1:value},{person2:value}....]
console.log($scope.price);
}
});
</script>
</body>
</html>

