What is dateFilter and where can I find out more about it?
Asked Answered
R

1

22

I am going through the Angular documentation on directives: http://docs.angularjs.org/guide/directive

One of the examples on the page (full working example here http://jsbin.com/osOQOYag/3/edit?html,js,output

angular.module('docsTimeDirective', [])
  .controller('Ctrl2', function($scope) {
    $scope.format = 'M/d/yy h:mm:ss a';
  })
  .directive('myCurrentTime', function($interval, dateFilter) {

    function link(scope, element, attrs) {
      var format,
          timeoutId;

      function updateTime() {
        element.text(dateFilter(new Date(), format));
      }

      scope.$watch(attrs.myCurrentTime, function(value) {
        format = value;
        updateTime();
      });

      element.on('$destroy', function() {
        $interval.cancel(timeoutId);
      });

      // start the UI update process; save the timeoutId for canceling
      timeoutId = $interval(function() {
        updateTime(); // update DOM
      }, 1000);
    }

    return {
      link: link
    };
  });

On the line:

.directive('myCurrentTime', function($interval, dateFilter) {

I cannot for the life of me find any information on the .directive prototype and cannot find any documentation on dateFilter anywhere either. Also, I know that dateFilter is found in the un-minified version of AngularJS (although the name disappears in the minified version). Can anyone provide some guidance (and possibly a link) explaining more about dateFilter and similar functions?

Roxy answered 26/12, 2013 at 17:33 Comment(1)
I agree, they shouldn't be using this method if it is not included in the documentation.Rightist
H
28

Date filter docs are here: http://code.angularjs.org/1.2.5/docs/api/ng.filter:date

Here's part of the docs that explain filter injection: http://code.angularjs.org/1.2.5/docs/guide/filter#using-filters-in-controllers-and-services

Filters are usually used in view expressions ({{myDate | date:'short'}}), but they can also be used in your JS code. Filters are injected by appending string Filter to the filter name (e.g. date -> dateFilter).

app.controller('MyCtrl', function($scope, dateFilter, lowercaseFilter){
  $scope.myDate = new Date();
  $scope.myDateFormatted = dateFilter($scope.myDate, 'shortDate');

  $scope.myString = 'Some String';
  $scope.myStringLowerCased = lowercaseFilter($scope.myString);
});

PLUNKER

Handmade answered 26/12, 2013 at 17:48 Comment(1)
I already understood everything you said EXCEPT the part about the appending 'Filter'. All makes sense now. Do you happen to have a link to THAT part of the documentation?Roxy

© 2022 - 2024 — McMap. All rights reserved.