$filter('date')在控制器中使用$scope变量作为格式时未更新格式

$filter('date') not updating format when using $scope variable for format in controller

本文关键字:格式 更新 变量 scope date filter 控制器      更新时间:2023-09-26

在angular中,我有一个简单的下拉菜单来设置数据格式
为了学习angularJS数据绑定,我想在控制器中截取选定的值,并在$filter("日期")中使用它来根据选定的格式更改显示的日期

以下是HTML和控制器代码:

<select ng-model="selector">
   <option value="dd/MM/yyyy">Euro</option>
   <option value="MM/dd/yyyy">USA</option>
   <option value="yyyy/MM/dd">JPN</option>
</select>
<span>
     Formatted Date: {{ formattedDate }}
</span>

$scope.selector = 'MM/dd/yyyy';
var nowDate = new Date();
$scope.formattedDate = $filter('date')(nowDate, $scope.selector);

通过从下拉列表中选择一个新值,选择器变量将被正确设置,但formattedDate不会更改,但它仍然初始化为第一个值

通过在HTML中使用角度过滤器,它可以很好地工作:

{{ nowDate | date : selector}}

观察方式

$watch添加到selector更改时的激发过滤器:

$scope.$watch(function () {
  return $scope.selector;
 },
  function (newValue, oldValue) {
    $scope.formattedDate = $filter('date')(nowDate, newValue);
 });

Fiddle中的演示1


ng-chage指令设置为<select>

$scope.fireFilter = function(){
    $scope.formattedDate = $filter('date')(nowDate, $scope.selector);
}

HTML

<select ng-model="selector" ng-change="fireFilter()">

Fiddle中的演示2


为了获得更好的性能,我将使用ng-chage方式