0

In my page I have:

 <h1>{{name | fontResize: 25:42}}</h1>

and I have a filter

 angular.module('myApp').filter('fontResize', function () {
                            return function (text, length, end) {
                              if (!text) {
                                return text;
                              }    
                              if (isNaN(length))
                                length = 10;    
                              if (end === undefined)
                                end = "...";    
                              if (text.length <= length || text.length - end.length <= length) {
                                $('h1').css('fontSize', '30px');
                                return text;
                              } else {
                                $('h1').css('fontSize', '12px');
                                return text;
                              }

                            };
                          });

How do I set the fontsize for my second argument (42) ?

1 Answer 1

1

Filters are not for manipulating DOM. You should create a directive.

There are 2 example directives:

First:

.directive('fontResize', function() {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      var size = attrs.size || '30px';
      var length = attrs.length || 10;

      attrs.$observe('text', function() {
        var text = attrs.text;
        if (text.length <= length) {
          elem.css('fontSize', size);
        } else {
          elem.css('fontSize', '12px');
        }
        elem.text(attrs.text);
      });
    }
  }
})

HTML:

<h1 font-resize text="{{name}}" size="42px"></h1>

And the second one:

.directive('fontResize2', function() {
  return {
    restrict: 'A',
    scope: {},
    link: function(scope, elem, attrs) {
      var size = attrs.size;
      var length = attrs.length || 10;

      scope.$watch(function() {
        return elem.text();
      }, function(newVal, oldVal) {
        setText(newVal)
      })

      function setText(text) {

        if (text.length <= length) {
          elem.css('fontSize', size);
        } else {
          elem.css('fontSize', '12px');
        }
        elem.text(attrs.text);

      }
    }
  }
});

HTML:

<h1 font-resize2 size="60px">{{name}}</h1>

You can extend them as you wish.

Here is the plunkr: http://plnkr.co/edit/uO9uYqcqLPuqAhJdtJ9m?p=preview

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

Comments

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.