Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a input field has a value in the controller using AngularJS

I'm quite simply trying to find out how I can retrieve the scopes information to see if it has a value or not in the controller.

I need to be able to write an if statement that says if this text input field is filled do this... if else do something different.

<form name="deadlineForm">
    <div class="app-select-date">
        <label for="deadline">Select deadline:</label>
        <input pickadate ng-model="deadline" format="dd/mm/yyyy" placeholder="Select deadline"/>
    </div>
</form>

What is the best way about writing this code in the controller?

like image 367
Max Lynn Avatar asked Mar 15 '23 02:03

Max Lynn


2 Answers

You have it bound to a variable (deadline) using ng-model="deadline".

Your check in the controller becomes as simple as:

if ($scope.deadline != null && $scope.deadline != "") {
    //do something
}

or this can be even simplified to

if ($scope.deadline) {
    //do something
}

Simple JSFiddle DEMO.

like image 141
SDekov Avatar answered Apr 24 '23 21:04

SDekov


Will this work for you ?

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
  angular.module('app', [])
  .controller('MainCtrl', function ($scope) {
    
    $scope.$watch('val', function (now, old) {
      if (now) {
        $scope.result = 'there is something';
      } else {
        $scope.result = 'there is nothing';
      }
    });
  });
</script>

<div ng-app='app' ng-controller='MainCtrl'>
  <input type="text" ng-model="val">  
  <span ng-bind='result'>
</div>
  
like image 44
Phizaz Avatar answered Apr 24 '23 20:04

Phizaz