AngularJS:选择指令验证

时间:2013-09-05 02:14:22

标签: javascript angularjs

我用select模板创建了一个指令,但我需要“name”标签,所以我可以进行验证,但我不知道如何添加它。我尝试添加attr但它没有用。

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;
        }
    };
});

1 个答案:

答案 0 :(得分:0)

您需要在“关键字”指令中添加“必需”才能进行验证。

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>',

这是更新的demo

希望这对你有所帮助。