Search code examples
javascriptjqueryangularjs

Angular date in ng-model value not pass to controller


When I click the CheckAvailability button, the date value doesn't pass to the controller.

<div class='input-group date'>
         <input ng-model="BookedFromDate" type="text" value=@DateTime.Now.ToString("dd/MM/yyyy") class="form-control BookedFDate" style="border-width: 0 0 2px 0;">
      <span class="input-group-addon">
          <i class="font-icon font-icon-calend"></i>
       </span>
                                       
   </div>

Angular:

$scope.CheckAvailability = function () {
    alert("Hello, " + $scope.BookedFromDate);
};

Solution

  • Forget ASP. In AngularJS input doesn't need a value. Simply populate the ng-model. You can do it in controller or with ng-init in HTML. To mask/filter the date, use $filter service. It's usually not used directly, so I suggest applying a filter in ng-init. AngularJS has a date filter for this purpose.

    Here is an example:

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
      $scope.now = new Date();
      $scope.CheckAvailability = function() {
        console.log("Date:", $scope.BookedFromDate);
      };
    });
    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    
    <body>
      <div ng-app="myApp" ng-controller="myCtrl">
    
        <div class='input-group date'>
          <input ng-model="BookedFromDate" 
                 type="text" 
                 ng-init="BookedFromDate = (now | date : 'dd/MM/yyyy')" 
                 class="form-control BookedFDate" 
                 style="border-width: 0 0 2px 0;">
    
          <span class="input-group-addon">
          <i class="font-icon font-icon-calend"></i>
        </span>
          <button ng-click="CheckAvailability()">Click</button>
        </div>
    
      </div>
    </body>
    </html>


    Alternatively change the type from text to date to completely ignore the filter and masking.

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
      $scope.BookedFromDate = new Date();
      $scope.CheckAvailability = function() {
        console.log("Date:", $scope.BookedFromDate);
      };
    });
    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    
    <body>
      <div ng-app="myApp" ng-controller="myCtrl">
    
        <div class='input-group date'>
          <input ng-model="BookedFromDate" 
                 type="date" 
                 class="form-control BookedFDate" 
                 style="border-width: 0 0 2px 0;">
    
          <span class="input-group-addon">
          <i class="font-icon font-icon-calend"></i>
        </span>
          <button ng-click="CheckAvailability()">Click</button>
    
        </div>
        
      </div>
    </body>
    </html>