我正在尝试验证从后端提供给我的一些表单字段。如果该字段名称需要该属性,我希望能够添加该属性。这是我的 html 端:
<div class="form-group">
<!-- ************** ADDITIONAL DYNAMIC FIELDS ******** -->
<div ng-repeat="field in assetFields" ng-cloak>
<div class="col-sm-6">
<input type="@{{field.element_type}}" name="@{{field.property}}" class="form-control input-lg" value="" id="@{{field.property}}">
</div>
</div>
这是 Angularjs 的一面:
$http.get('/getAssetFeilds/'+$scope.assetType).success(function(data)
{
console.log(data);
$scope.assetFields = data;
//loop through the array of json objects
angular.forEach(data, function(input, key){
//get the type of element
if(input.element_type == 'text'){
//loop through input validations
angular.forEach(input.validations, function(value, key){
//check if this input type field is required
if(value == 'required'){
console.log("#"+input.property);
//find the element id value and add required attribute
angular.element("#"+input.property).attr('required', 'required');
}
});
}
});
});
但是,当我检查元素时,它没有添加属性。这不起作用的原因可能是什么?我认为这会起作用。
最佳答案
属性中“@”的用途是什么?
id="@{{field.property}}"
目前为元素设置的 id 在 id 名称之前有“@”,但是您正在查找 "#"+ input.property
并在其中添加“@”符号,"#@"+ input.property
会给你一个无效
错误。
您还需要将 required
属性的添加包装在 $timeout
中,以确保首先呈现 DOM 元素。
$timeout(function() {
angular.element("#" + input.property).attr('required', 'required');
});
这是一个plnk它的工作原理。
关于javascript - AngularJS 动态表单字段添加必需属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40772821/