简体   繁体   中英

AngularJS: Select directive validation

I created a directive with select template but i need the "name" tag so i can put a validation and i don't know how to add that. I tried adding attr but it didn't work.

Here is the fiddle

<form name="newForm" ng-submit="save()">
                <div>
                    Name: <input required ng-model="newSupplier.Name" name="myName" type="text" required/>
                    <span ng-show="newForm.myName.$error.required">*</span>
                    <br />
                    Status: <keywords name="myStatus" title="Choose Status" label="" array="myKeyword" keyword-type="ActivityType" supplier-id="newSupplier.Id" opt-value="Id" opt-description="Description"></keywords>
                    <span ng-show="newForm.myStatus.$error.required">*</span>
                    <br>
                    <button type="submit">Save</button>
                    <br /><i>How to save the ID of the selected dropdown?</i>
                    </div>
                    </form>

JS

app.directive('keywords', function(){
    return {
        restrict: 'E',
        scope: {
            array: '=',
            supplierId : '='
        },
        template:   '<label>{{label}}</label>' +
        '<select ng-model="supplierId" ng-options="a[optValue] as a[optDescription] for a in array | filter: keywordType">' +
                        '<option style="display: none" value="">-- {{title}} --</option>' +
                    '</select>',
        link: function (scope, element, attrs) {
            scope.label = attrs.label;  
            scope.title = attrs.title;
            scope.optValue = attrs.optValue;
            scope.optDescription = attrs.optDescription;
            scope.keywordType = attrs.keywordType;
        }
    };
});

You need to add "required" to your "keywords" directive to make validation works.

template: '<label>{{label}}</label>' +
          '<select ng-model="supplierId" ng-options="a[optValue] as a[optDescription] for a in array | filter: keywordType" required>' +
          '<option style="display: none" value="">-- {{title}} --</option>' +
          '</select>',

This is the updated demo

Hope this is helpful for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM