Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically naming input controls in angularjs

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;
    };
like image 352
erin c Avatar asked Nov 23 '25 10:11

erin c


1 Answers

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.

Update

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.

like image 102
Jerrad Avatar answered Nov 24 '25 23:11

Jerrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!