ng-model值中的AngularJS日期未传递给控制器

时间:2018-06-19 13:57:20

标签: javascript jquery angularjs

当我单击CheckAvailability按钮时,日期值不会传递给控制器​​

<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>

Anguler:

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

2 个答案:

答案 0 :(得分:2)

忘记ASP。在AngularJS中,输入不需要值。只需填充ng-model。您可以在控制器中执行此操作,也可以在HTML中使用ng-init进行操作。要屏蔽/过滤日期,请使用$filter服务。通常不直接使用它,因此建议在ng-init中应用过滤器。 AngularJS为此提供了一个date过滤器。

这里是一个例子:

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>


或者将类型从text更改为date,以完全忽略过滤器和掩码。

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>

答案 1 :(得分:0)

希望此代码有助于在 value 标签中使用较少的标签,因为我们将值双向绑定。

<body ng-app="app">
    <div ng-controller="EditCtrl">
      <input type="text" ng-model="item.title" />
      <input type="date" ng-model="item.date" />
      {{item.date}}
    </div>
  </body>