Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - how to get ng-message required error to display and disable input button at the same time

I want an error message to appear if the user clicks submit with no content, and I want the submit button to be disabled. I can get either one working, but not both at the same time.

The code below brings up the message but allows an empty todo item.

<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>

This version disables the submit button but doesn't bring up the message

<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>

I presume this is because the message can't be displayed when the input button is disabled because nothing has been submitted?

I've tried using $disabled and $invalid instead but they haven't worked.

like image 689
vtechmonkey Avatar asked Apr 27 '15 14:04

vtechmonkey


1 Answers

I removed the conflicting ng-if on the ng-message element. Here is a working plunk showing the fixed code.

http://plnkr.co/edit/gL0GoFT47mSeydKReLuD

My assumption is that you forgot to inject the 'ngMessages' module as an external dependency.

You can fix your code like this:

var app = angular.module('plunker', ['ngMessages']);
like image 171
km1882 Avatar answered Oct 19 '22 17:10

km1882