I have a input element which I am trying to name dynamically, but I had no luck so far using angular js.
neither
<input type="text" name="resource.Name" ng-model="resource.Value" ng-required="resource.IsRequired">
nor
<input type="text" name="{{resource.Name}}" ng-model="resource.Value" ng-required="resource.IsRequired">
works for me. When I try to access name attribute it always comes back as resource.Name instead of the value it contains. The main reason I am trying to name this input control is validation, if user does not enter text in the field, I would like to tell them which textbox is required. If there is any angular directive I can use for that purpose I am ready to use them as well.
Can anyone tell me how to achieve this.
My validation function is as follows:
window.resourcesValidation = function ($scope, $rootScope, $alert) {
var subscriptions = $scope.scopeData.Subscriptions;
var isValidated = true;
if ($scope.resourceDataForm && $scope.resourceDataForm.$error && $scope.resourceDataForm.$error.required) {
var missingFields = [];
angular.forEach($scope.resourceDataForm.$error.required, function (value, key) {
isValidated = false;
missingFields.push("-" + value.$name);
});
$alert.error("Please fill in the all required fields.\r\n" + missingFields.join("\r\n"));
}
if (isValidated)
$scope.saveChanges(subscriptions);
return isValidated;
};
Try this:
<input type="text" ng-attr-name="{{resource.Name}}" ng-model="resource.Value" ng-required="resource.IsRequired">
From the docs:
If an attribute with a binding is prefixed with the ngAttr prefix (denormalized as ng-attr-) then during the binding will be applied to the corresponding unprefixed attribute.
Although name="{{resource.Name}}" should work in this case as well.
I found a solution here: Dynamic validation and name in a form with AngularJS
Here's a plunker that I made.
Sounds like this issue may be fixed in Angular 1.3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With