简体   繁体   English

在Controller中而不是在Expression中使用过滤器

[英]Using filters in Controller instead of in Expression

I am using date filter of 'Angular-UI' (Datepicker) in which I can filter date in dd-mm-yy format. 我正在使用“ Angular-UI”(日期选择器)的日期过滤器,在其中可以以dd-mm-yy格式过滤日期。 Following is the code: 以下是代码:

<input id="fromDate" name="fromDate" ng-click="open($event,'fromDate')" data-ng-model="filter.fromDate" datepicker-popup="{{format}}" is-open="datepickers.fromDate" datepicker-options="dateOptions" />
{{filter.fromDate|date:'dd-mm-yy'}}

This is eazy as the datepicker now provides me date in required format. 这很容易,因为日期选择器现在为我提供了所需格式的日期。 However, similar thing if I try to do in controller, I am unable to achive. 但是,如果我尝试在控制器中执行类似操作,则无法实现。

var app = angular.module('myApp',['ui.bootstrap']); 
app.controller = ('myCtrl', function($scope, $filter) { 
$scope.filter.fromDate = ""; 
$scope.reqDate = ""; 
$scope.reqDate = $filter('$scope.filter.fromDate', date:'dd-mm-yy'); 
});

Can someone help me out? 有人可以帮我吗?

First of all, the date filter is not part of Angular-UI. 首先,日期过滤器不是Angular-UI的一部分。 It's part of AngularJS itself. 它是AngularJS本身的一部分。

To get a filter, named 'date', from the code, you use the $filter service, and pass it the name of the filter: 'date' . 要从代码中获取名为“ date”的过滤器,请使用$ filter服务,并将其名称传递给过滤器: 'date' It returns the filtering function: 它返回过滤功能:

var dateFilter = $filter('date');

This function takes the input to filter as first argument (ie what you put before the | in the view), and additional arguments if needed (ie what you put after : in the view): 这个函数的输入滤波器作为第一个参数(即你之前把|视图)如果需要的话,和附加参数(即你后放什么:在视图中):

$scope.reqDate = dateFilter($scope.filter.fromDate, 'dd-MM-yy');

The whole thing can of course be done in a single line: 整个过程当然可以在一行中完成:

$scope.reqDate = $filter('date')($scope.filter.fromDate, 'dd-MM-yy');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM