Angularjs - 如何获取ng-message所需的错误以同时显示和禁用输入按钮

时间:2015-04-27 14:13:30

标签: angularjs forms message disabled-input

如果用户点击没有内容的提交,我希望显示一条错误消息,并且我希望禁用提交按钮。 我可以让任何一个工作,但不能同时工作。

下面的代码会显示消息但允许空的待办事项。

<form name="todoForm" novalidate >


    <div ng-messages="todoForm.new.$error" ng-if="todoForm.$submitted"><div ng-message="required">Add Your Item Below...</div></div><!--message appears until valid input is entered--> 

    <input type="text" name="new" placeholder="start typing..." autofocus data-ng-model="newTodo" required=""/>

    <button input type="submit" ng-click="addTodo()" >Add To List</button><!--disables form if form not valid-->

</form>

此版本禁用提交按钮,但不会显示消息

<form name="todoForm" novalidate >


    <div ng-messages="todoForm.new.$error" ng-if="todoForm.$submitted"><div ng-message="required">Add Your Item Below...</div></div><!--message appears until valid input is entered--> 

    <input type="text" name="new" placeholder="start typing..." autofocus data-ng-model="newTodo" required=""/>

    <button input type="submit" ng-click="addTodo()" data-ng-disabled="todoForm.$invalid" >Add To List</button>
</form>

我认为这是因为当输入按钮被禁用时因为没有提交任何内容而无法显示消息?

我尝试过使用$ disabled和$ invalid,但是他们没有用。

1 个答案:

答案 0 :(得分:1)

我删除了ng-message元素上的冲突ng-if。这是一个显示固定代码的工作插件。

http://plnkr.co/edit/gL0GoFT47mSeydKReLuD

我的假设是您忘记将'ngMessages'模块注入外部依赖项。

您可以像这样修复代码:

import java.awt.*;
import java.lang.String.*;
import java.awt.event.*;
import java.applet.Applet;
/*</applet code="Fact.class",height=200 width=200></applet>*/
public class Fact extends Applet implements ActionListener
{
    String str;
    Button b;
    TextField t1,t2;
    Label l1,l2;
    public void init()
    {
        Panel p=new Panel();
        p.setLayout(new GridLayout());
        add(l1=new Label("Enter integer"));
        add(t1=new TextField(20));
        add(l2=new Label("Factorial value is"));
        add(t2=new TextField(20));
        b.addActionListener(this);              
    }
    public void actionPerformed(ActionEvent e)
    {
        int i,n,f=1;
        n=Integer.parseInt(t1.getText());
        for(i=1;i<=n;i++)
            f=f*i;
        t2.setText(String.valueOf(f));
        repaint();        
    }
}