您好我想在我的应用中为每个输入使用angular指令。我已经制作了一些具有许多属性的简单指令,但我不知道如何进行验证。验证需要唯一的'name'参数,但我在一个表单中使用了很多输入,所以我试图通过它:
<form name="form" ng-controller="sampleController" novalidate>
<div data-input-row data="form.father.name" name="fatherName" placeholder="placeholder" label="father name"></div>
<div data-input-row data="form.father.surname" name="fatherSurname" placeholder="placeholder" label="father surname"></div>
<div data-input-row data="form.mother.name" name="motherName" placeholder="placeholder" label="mother name"></div>
<div data-input-row data="form.mother.surname" name="motherSurname" placeholder="placeholder" label="mother surname"></div>
</form>
指令:
restrict: 'A',
scope: {
data: '=',
name: '@',
required: '@',
type: '@',
placeholder: '@',
label: '@',
rendered: '@'
},
link: function(scope, element, attrs) {
//1: maybe someone knows better way for default parameters values than this ifs ?
if (!attrs.type) { attrs.type = 'text'; }
if (!attrs.rendered) { attrs.rendered = 'true'; }
if (!attrs.required) { attrs.required = 'false'; }
},
templateUrl: UrlConfig.BasicUrlConfig.APPLICATION_URL + '/app/modules/directives/input/inputRow.html'
HTML:
<div ng-if="rendered == 'true'" class="input-control">
<label for="input">{{label}}</label>
//2: maybe someone knows better way for optional required param than copy of input ?
<input id="input" ng-if="required != 'true'" type="{{type}}" name="{{name}}" ng-model="data" placeholder="{{placeholder}}" />
<input id="input" ng-if="required == 'true'" type="{{type}}" name="{{name}}" ng-model="data" placeholder="{{placeholder}}" required/>
//3: name should be unique so it should be parametrized, but how to type it then: ng-show="form.{{name}}.$invalid" ?????
//this section is never showing up.
<span class="error" ng-show="form.{{name}}.$invalid && form.{{name}}.$dirty">
{{label}} required!
</span>
<span class="error" ng-show="form.{{name}}.$error.number">
{{label}} not valid number!
</span>
答案 0 :(得分:0)
首先,您应该使用ng-required
并使用[]
作为动态对象名称。试试这个:
<div ng-if="rendered == 'true'" class="input-control">
<label for="input">{{label}}</label>
//2: ng-required is a saviour
<input id="input" ng-required="required == 'true'" type="{{type}}" name="{{name}}" ng-model="data" placeholder="{{placeholder}}" />
//3: Use [ variable_name ] for dynamic object name like object[ variable_name ]
<span class="error" ng-show="form[name].$invalid && form[name].$dirty">
{{label}} required!
</span>
<span class="error" ng-show="form[name].$error.number">
{{label}} not valid number!
</span>
</div>
我仍然不确定它是否会起作用,因为form
超出了范围。我认为你也必须通过指令传递form变量。