1
我正在尝试创建一个<input-field>
指令,该指令具有基本的表单验证。AngularJS将模型连接到ng-show
我需要的标记,以便能够像这样
<div class="form-group has-feedback">
<input name="street_address_1" ng-model="customer.street_address_1" />
<span class="fa fa-check fa-fw" ng-show="customerCreateForm.street_address_1.$valid"></span>
<span class="fa fa-times fa-fw" ng-show="customerCreateForm.street_address_1.$invalid"></span>
</div>
我开始写指令,但ng-show
属性不会链接到模型准确。
myApp.directive('inputField', function() {
return {
restrict: 'E',
scope:{
fieldName: '@name',
fieldModel: '=ngModel',
fieldForm: '=form',
required: '@'
},
replace: true,
template: '<div class="form-group has-feedback">' +
' <input name="{{ fieldName }}" ng-model="fieldModel" ng-required="required" />' +
' <span class="fa fa-check fa-fw form-control-feedback" ng-show="fieldForm[fieldName][$valid]"></span>' +
'</div>'
}
});
这就是我如何使用指令:
<input-field name="street_address_1" ng-model="customer.street_address_1" form="customerCreateForm" required />
编辑:
这里是一个plunkr:
http://plnkr.co/edit/gVY2BpkqNSKBTHcjteNw?p=preview
能否请您发布的这个plunkr。 – Sylvain
不知道我遵循你在做什么,但你看过指令的transclude选项吗?它允许你传递任意标记到你的指令的模板中......另外,当前的一个plunkr肯定会有帮助 –
另外一个使用transclude的解决方案可能需要使用ngModelController,因此你的指令可以和任何ng-model值一起工作您通过的“任意”标记 –