end-user
end-user

Reputation: 2947

how can I pass a filter to a directive in Angular?

Similar to this question, I have a directive that I want to use in a couple different situations. I'm passing in a value that it will work with, but I'd also like to pass in a filter to apply to it. What's the right syntax for doing this?

app.directive('showMe', function() {
  return {
    restrict: 'E',
    scope: {
      value: '=',
      filter: '=',
      placeholder: '='
    },
    templateUrl: 'show-me.html'
  };
});

template:

<input ng-model="value" ng-show="editMode" placeholder="{{placeholder}}" />
<p ng-hide="editMode">{{(value | percent)||placeholder}}</p>

use:

<show-me value="item.discount" filter="percent" placeholder="0%" />

expected result:

<input value="25" placeholder="0%" />
or
<p>25%</p>

Upvotes: 0

Views: 1173

Answers (2)

Iain J. Reid
Iain J. Reid

Reputation: 988

You could achieve this at a basic level by using the method below; simply use the filter provider within your directive controller, to parse the given value. For example:

<my-directive value="1461782417" filter="date"></my-directive>

Within "myDirective" you could implement the filter very easily like this:

angular
  .module('myApp')
  .directive('myDirective', {
    restrict: 'E',
    template: '<span>{{displayValue}}</span>',
    scope: {
      value: '=',
      filter: '='
    },
    controller: ['$scope', '$filter', function ($scope, $filter) {
      // Pass the value
      $scope.displayValue = $filter($scope.filter)($scope.value);
    }]
  });

Upvotes: 3

WebDevDaniel
WebDevDaniel

Reputation: 74

    .filter('percent', function () {
        return function (text, length, end) {
            if (text == null || text == '') text = '0';
            text = parseInt(text) / 100;
            return text.toFixed(2);
    };

Upvotes: 0

Related Questions