vigamage vigamage - 3 months ago 12
AngularJS Question

Check whether input field is empty in Controller - AngularJS

I just started learning AngularJS. In a testing program I wrote, I need to check whether my input field is empty or not inside the controller(script).

Following is the code I 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, as the output, I expected to see
pls enter something
. But I cannot see anything.

But If I change the script in to following with some small changes, it shows me
Something Entered
as 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 is wrong here? As far as I understand, the first one should work if the second one works as expected. Otherwise, both should not work.

I think I have not understood something very basic. If so, please describe me what I have not read about.

Thank You..!

Answer

The problem is that you are only checking if the scope property is filled in once. (this happens when angular initializes the controller) What you need to do is add an ng-change to the html and then when the model changes the function will fire again.

In the function you do your logic again. like so :

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 your html:

<div ng-controller="ExampleController">
    <input type="text" ng-change="checkContent()" ng-model="userFirstName" required/><br>
    <p ng-bind="msg"></p>
</div>
Comments