AngularJS:如何在控制器中手动将输入设置为 $valid? [英] AngularJS: How do I manually set input to $valid in controller?

查看:28
本文介绍了AngularJS:如何在控制器中手动将输入设置为 $valid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 TokenInput 插件并使用 AngularJS 内置的 formController 验证.

Using the TokenInput plugin and using AngularJS built-in formController validation.

现在我正在尝试检查该字段是否包含文本,然后将字段设置为有效(如果包含).使用该插件的问题在于它创建了自己的输入,然后是一个用于 stlying 的 ul+li.

Right now I'm trying to check if the field contains text, and then set field to valid if it does. The issue with using the plugin is it creates it's own input and then a ul+li for stlying.

我可以访问控制器中的 addItem (formname) 和我的功能,我只需要将其设置为 $valid.

I have access to addItem (formname) and my capablities in the controller, I just need to set it to $valid.

标记.

<form class="form-horizontal add-inventory-item" name="addItem">
     <input id="capabilities" name="capabilities" token-input data-ng-model="inventoryCapabilitiesAutoComplete" data-on-add="addCapability()" data-on-delete="removeCapability()" required>
     <div class="required" data-ng-show="addItem.capabilities.$error.required" title="Please enter capability."></div>
</form>

JS.

$scope.capabilityValidation = function (capability) {
  if (capability.name !== "") {
    addItem.capabilities.$valid = true;
    addItem.capabilities.$error.required = false;
  } else {
    addItem.capabilities.$valid = false;
    addItem.capabilities.$error.required = true;
  }
};

当 TokenInput 输入并传入对象时,我正在运行功能验证函数.

I'm running the capabilityValidation function when TokenInput has something entered and passing in the object.

在我的输入中发现 ng-model 可以执行一些操作并获得自动完成结果,这就是为什么我无法让 ng-valid 工作,因为它是基于模型的.

Found out ng-model on my input does stuff and gets the autocomplete results, which is why I can't get ng-valid to work since it's based on the model.

$scope.inventoryCapabilitiesAutoComplete = {
  options: {
    tokenLimit: null
  },
  source: urlHelper.getAutoComplete('capability')
};

我没有编写这个自动完成实现,有没有另一种方法可以做到这一点,我可以访问 ng-model attr 并将模型函数移到其他地方?

I didn't write this autocomplete implementation, is there another way to do this where I would have access to the ng-model attr and move the model function somewhere else?

推荐答案

您不能直接更改表单的有效性.如果所有后代输入都有效,则表单有效,如果不是,则无效.

You cannot directly change a form's validity. If all the descendant inputs are valid, the form is valid, if not, then it is not.

您应该做的是设置输入元素的有效性.像这样;

What you should do is to set the validity of the input element. Like so;

addItem.capabilities.$setValidity("youAreFat", false);

现在输入(以及表单)无效.您还可以查看导致失效的错误.

Now the input (and so the form) is invalid. You can also see which error causes invalidation.

addItem.capabilities.errors.youAreFat == true;

这篇关于AngularJS:如何在控制器中手动将输入设置为 $valid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆