我有一个基于angular-fullstack项目的简单应用程序,其中有很多非常相似的输入字段。
目标:使输入字段动态化,将它们移至指令,以便将输入字段代码移出模板-更好地维护,减少代码重复。
问题:我无法在动态生成的字段上访问诸如$valid
之类的值,因为它们未设置
我有一个非常简单的指令:
'use strict';
const angular = require('angular');
export default angular.module('testApp.inputText', [])
.directive('inputText', function() {
return {
template: require('./inputText.html'),
restrict: 'EA',
scope: false,
transclude: true,
link: function(scope, element, attrs) {
scope.fieldName = attrs.name;
}
};
})
.name;
使用简单的模板:
<input
type="text"
name="fieldName"
class="uk-input"
ng-model="build.justTest.view[fieldName].value"
>
我这样称呼:
<form name="build.justTest.view" novalidate>
<input-text name="new-test-input"></input-text>
</form>
当我使用ng-inspector检查动态字段时,它看起来像这样:
{value: "1234"}
与模板中定义的静态输入字段进行比较:
{$viewValue: "", $modelValue: "", $$rawModelValue: "", $validators: {…}, $asyncValidators: {…}, …}$$animate: {on: ƒ, off: ƒ, pin: ƒ, enabled: ƒ, cancel: ƒ, …}$$attr: Attributes {$attr: {…}, $$element: JQLite(1), type: "text", name: "giftDescription", class: "uk-input uk-height-small", …}$$classCache: {ng-valid: true, ng-invalid: false, ng-valid-minlength: true, ng-valid-maxlength: true}$$currentValidationRunId: 8$$element: JQLite [input.uk-input.uk-height-small.ng-pristine.ng-untouched.ng-valid.ng-empty.ng-valid-minlength.ng-vali…]$$exceptionHandler: ƒ (exception, cause)$$lastCommittedViewValue: ""$$ngModelGet: ƒ (s,l,a,i)$$ngModelSet: ƒ (s,v,l)$$parentForm: {$$controls: Array(16), $error: {…}, $$success: {…}, $pending: undefined, $name: "build.justTest.view", …}$$parse: ƒ $parse(exp, interceptorFn)$$parsedNgModel: ƒ (s,l,a,i)$$parsedNgModelAssign: ƒ (s,v,l)$$parserValid: undefined$$pendingDebounce: null$$q: ƒ $Q(resolver)$$rawModelValue: ""$$success: {minlength: true, maxlength: true}$$timeout: ƒ timeout(fn, delay, invokeApply)$asyncValidators: {}$dirty: false$error: {}$formatters: [ƒ]$invalid: false$modelValue: ""$name: "giftDescription"$options: ModelOptions {$$options: {…}}$parsers: []$pending: undefined$pristine: true$render: ƒ ()$touched: false$untouched: true$valid: true$validators: {minlength: ƒ, maxlength: ƒ}$viewChangeListeners: [ƒ]$viewValue: ""value: "12345678910"$$scope: Scope {$$childTail: ChildScope, $$childHead: ChildScope, $$nextSibling: null, $$watchers: Array(86), $$listeners: {…}, …}__proto__: Object
谁能告诉我为什么在指令和
的输入中未定义$valid
谢谢!
答案 0 :(得分:0)
您是否尝试将以下内容添加到指令定义中?
...,
require: '^form',
restrict: 'EA',
...
我一直以为输入是自动完成的。但是,当您使用指令时,必须定义它。
然后,您可以在指令的链接功能中访问表单,如下所示:
link: function(scope, element, attrs, myForm) {...}