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

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

The code below triggers a message, but resolves an empty todo element.

<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 does not display a 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 assume this is because the message cannot be displayed when the enter button is disabled because nothing has been sent?

I tried using $ disabled and $ invalid, but they did not work.

+7
angularjs forms message disabled-input
source share
1 answer

I removed the conflicting ng-if in the ng-message element. Here is a desktop showing a fixed code.

http://plnkr.co/edit/gL0GoFT47mSeydKReLuD

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

You can fix your code as follows:

 var app = angular.module('plunker', ['ngMessages']); 
+1
source share

All Articles