angularjs - How to validate forms with dynamic ngMessages -


this plunk has form field allows enter aaa. note error message set in controller, not in html. when user clicks on submit should see message, message not shown. what's wrong code?

html

<body ng-app="ngmessagesexample" ng-controller="ctl">    <form name="myform" novalidate ng-submit="submitform()">     <label>       field valid when 'aaa'         <input type="field1"              ng-model="data.field1"              name="field1"              required />     </label>     <div ng-messages="myform.field1.$error" style="color:red">         <div ng-message-exp="required">{{errormsg}}</div>     </div>    <br/><br/>   <button style="float:left" type="submit">submit</button> </form>  </body> 

javascript

var app = angular.module('ngmessagesexample', ['ngmessages']);  app.controller('ctl', function ($scope) {    $scope.submitform = function() {     if ($scope.field1 != 'aaa')         $errormsg = "this field should 'aaa'";     else         $errormsg = "";   };        }); 

forget previous answer. easiest , robust make new directive.

var app = angular.module('ngmessagesexample', ['ngmessages']); app.directive("aaa", function() {     return {         restrict: "a",          require: "ngmodel",          link: function(scope, element, attributes, ngmodel) {             ngmodel.$validators.aaa = function(modelvalue) {                   return modelvalue === 'aaa';             }         }     }; }); 

and controller:

app.controller('ctl', function ($scope) {    $scope.data = {     field1: ""   }   $scope.submitform = function(){      //extra whatever code   } }); 

your html should this:

<body ng-app="ngmessagesexample" ng-controller="ctl">   <form name="myform" novalidate ng-submit="submitform(myform)">     <label>this field valid when 'aaa' is</label>       <input type="field1"          ng-model="data.field1"          name="field1"          required aaa/>     <div ng-messages="myform.field1.$error" style="color:red">       <div ng-message="required">field required!!</div>       <div ng-message="aaa">field must 'aaa'</div>     </div>     <button style="float:left" type="submit">submit</button>   </form> </body> 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -