AngularJS:无法在指令输入中访问$ valid

问题描述 投票:0回答:1

我有一个基于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没有在指令的输入上定义

提前致谢!

angularjs angular-directive angular-fullstack
1个回答
0
投票

您是否尝试将此以下内容添加到指令定义中?

...,
require: '^form',
restrict: 'EA',
...

我一直以为这是通过输入自动完成的。但是当你使用指令时,你必须定义它。

然后,您可以访问指令的link函数中的表单,如下所示:

link: function(scope, element, attrs, myForm) {...}
© www.soinside.com 2019 - 2024. All rights reserved.