2

I am trying to create a directive in which I need to format a value according to a filter which may vary (depending on the field, it could be "number:2", "date"... or whatever).

So I want to define the filter when I use the directive in the markup. Scenario is depicted through this plunker: http://embed.plnkr.co/N2zKITFpUQMxmylAAGlt/preview

So far filter is not applied or errors are raised.

What's the right way to implement it? Thanx

2 Answers 2

3

Here's one way to do it using template:function(elem,attrs)

app.directive('editableField', function() {
    return {
        restrict: 'A',
        replace: true,
      template:function(elem,attrs) {

        return '<div>' +
            '<input ng-model="editableModel" />' +
            '<div class="output">{{editableModel|'+attrs.editableFilter+' }}</div>' +
             '</div>';
      },

     /* if using in a form....I would remove the isolated scope*/
       scope: {
          editableModel: '='
      },
      controller: function($scope) {},
      link: function($scope, $element, $attrs, $filter) {
        var input = $element.find('input');
        input.bind('click', function () {
            this.select();
        });
      }
    };
});

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Thanx, so far the best solution I have seen.
3

Here is a working Plunkr:

http://plnkr.co/edit/nZgah7PtGRVMWBgKu7V8?p=preview

There are two examples, one that formats it as a float, and one that supposedly formats it as a date. The formatting itself I didn't do as it is fairly trivial.

5 Comments

Thanx. It could be a second solution, but so far I find the previous answer (from charlietfl) more clean and easy.
I would say that my solution is cleaner as it doesn't involve concatenating strings in the template. Besides, mine will work for complex objects that you can pass to your filter.
I agree with you on that, but I do not like the way your example switches on filter type.
You can check out my edited solution which is even shorter: gist.github.com/anonymous/3d2d79d6ef2d87fae0fa
@MatteoPiazza, you don't need to use my filter switching example. You could as easily use the built-in angular filters just by modifying a line of code. And by adding just two or three lines of code you could make it use both custom filters and angular built-in filters. What I am saying, though, is concatenating a filter definition into your template is weird. You could do it in a cleaner way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.