Check whether input field is empty in Controller - AngularJS -


i started learning angularjs. in testing program wrote, need check whether input field empty or not inside controller(script).

following code wrote

<div ng-controller="examplecontroller">     <input type="text" ng-model="userfirstname" required/><br>     <p ng-bind="msg"></p> </div>  <script>     var mainapp = angular.module("mainapp", []);     mainapp.controller('examplecontroller', function ($scope) {         if($scope.userfirstname.length === 0){           $scope.msg = "pls enter something";        }else{           $scope.msg = "something entered";        }     }); </script> 

here, output, expected see pls enter something. cannot see anything.

but if change script in following small changes, shows me something entered expected.

<script>    var mainapp = angular.module("mainapp", []);    mainapp.controller('examplecontroller', function ($scope) {         $scope.userfirstname = 'something';         if($scope.userfirstname.length === 0){              $scope.msg = "pls enter something";         }else{              $scope.msg = "something entered";         }    }); </script> 

what wrong here? far understand, first 1 should work if second 1 works expected. otherwise, both should not work.

i think have not understood basic. if so, please describe me have not read about.

thank you..!

the problem checking if scope property filled in once. (this happens when angular initializes controller) need add ng-change html , when model changes function fire again.

in function logic again. :

var mainapp = angular.module("mainapp", []);    mainapp.controller('examplecontroller', function ($scope) {         $scope.userfirstname = '';         $scope.checkcontent = function(){           if($scope.userfirstname.length === 0 || typeof $scope.userfirstname === 'undefined'){              $scope.msg = "pls enter something";           }else{              $scope.msg = "something entered";            }          }      }); 

then in html:

<div ng-controller="examplecontroller">     <input type="text" ng-change="checkcontent()" ng-model="userfirstname" required/><br>     <p ng-bind="msg"></p> </div> 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -