使用$范围的变量在控制器的格式时过滤器$('日')不更新格式 [英] $filter('date') not updating format when using $scope variable for format in controller

查看:131
本文介绍了使用$范围的变量在控制器的格式时过滤器$('日')不更新格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角我有一个简单的下拉到设定的数据格式。
对于学习angularJS数据绑定的缘故,我想拦截在控制器所选择的值,并有使用它过滤$('日')内,以改变显示的日期,根据所选格式。


下面是HTML和控制器code:

 <选择NG模型=选择>
   <期权价值=DD / MM / YYYY>欧元和LT; /选项>
   <期权价值=MM / DD / YYYY>美国< /选项>
   <期权价值=YYYY / MM / DD>&JPN LT; /选项>
< /选择>
<跨度>
     格式化的日期:{{formattedDate}}
< / SPAN>
$ scope.selector ='MM / DD / YYYY';
VAR nowDate =新的日期();
$ scope.formattedDate = $过滤器('日期')(nowDate,$ scope.selector);

通过从下拉选择一个新的值向下时,选择变量设置正确,但formattedDate不发生变化,但它仍初始化为第一值。搜索结果
通过在HTML中使用的角度过滤器正常工作:

  {{nowDate |日期:选择}}


解决方案

观看方式

添加 $观看火上选择过滤器的变化:

  $范围。$表(函数(){
  返回$ scope.selector;
 },
  功能(为newValue,属性oldValue){
    $ scope.formattedDate = $过滤器('日期')(nowDate,为newValue);
 });

在<大骨节病> 小提琴

演示1

NG-CHAGE方式

设置 NG-CHAGE 指令&LT;选择&GT;

  $ scope.fireFilter =功能(){
    $ scope.formattedDate = $过滤器('日期')(nowDate,$ scope.selector);
}

HTML

 &LT;选择NG模型=选择NG变化=fireFilter()&GT;

演示2 <大骨节病> 小提琴


有关更好的表现,我会用 NG-CHAGE 办法

In angular I have a simple drop down to set a data format.
For the sake of learning the angularJS data binding, I would like to intercept the selected value in the controller and use it there within a $filter('date') to change the displayed date, according to the selected format.

Below is the HTML and controller code:

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

By selecting a new value from the drop down, the selector variable is set correctly, but the formattedDate does not change, but it remains initialized to the first value.

By using the angular filter in HTML it works fine:

{{ nowDate | date : selector}}

解决方案

Watch way

Add $watch to fire filter on selector change:

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

Demo 1 in Fiddle


ng-chage way

Set ng-chage directive to <select>

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

HTML

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

Demo 2 in Fiddle


For better performance I would use ng-chage way

这篇关于使用$范围的变量在控制器的格式时过滤器$('日')不更新格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆