AngularJS filter causes IE8 to not render two-way binding

By : Scott
Source: Stackoverflow.com
Question!

I have a bizarre issue with IE8 where if I try to render a $scope variable in a template via AngularJS's two-way data binding, it won't replace {{child.name}} with the proper value. This surely has something to do with the inefficiency of the following filter:

  filter('truncate', function() {
    return function(name) {
      // It's just easier to use jQuery here
      var windowWidth = $(window).width(),
          nameElement = $('a:contains("' + name + '")'),
          truncPnt = Math.floor(name.length * 0.9);

      while (nameElement.width() > windowWidth * 0.75 && truncPnt > 6) {

        truncPnt = Math.floor(truncPnt * 0.9);
        name = name.substring(0, truncPnt);
        nameElement.text(name + ' ...');
      }
      return name;
    }
  });

I then use this filter with an ng-repeat with:

<a class="entity-name" href="{{child.url}}" title="{{child.name}}" ng-cloak>{{child.name|truncate}}</a>

The overall goal is to have the variable passed into the filter truncated down depending on the width of the screen, replacing any truncated characters with " ...". I'm fairly confident this filter is the cause since I have a similar function that gets called on a .resize() of the $(window) handler, and if I were to take IE8, and resize the browser window, it causes the {{child.name}} to render as the proper value, but only if I resize the browser.

UPDATE:


So I've gotten rid of the above filter, and replaced it with a very similar directive. This is my first attempt at creating a custom directive, so I'm fairly certain it could be done better, minus the obvious flaw that I cannot seem to work around currently. The directive is as follows:

.directive('truncate', function() {

  return {
    restrict: 'A',
    replace: true,
    template: '<a class="entity-name" href="{{child.url}}" title="{{child.name}}">{{child.display}}</a>',
    link: function(scope, element, attr) {
      var widthThreshold = $(element[0]).parent().parent().width() * 0.85;

      scope.$watch('child', function(val) {
        var elementWidth = $(element[0]).width(),
            characterCount = scope.child.name.length;

        while ($(element[0]).width() > widthThreshold || characterCount > 5) {
          characterCount--;
          scope.child.display = scope.child.name.substring(0, characterCount) + ' ...';
        }
      });
    }
  }
});

And I replace the partial to simply:

<a truncate="child"></a>

The differences in this as opposed to the filter are as follows (minus the obvious filter vs. directive):

  1. Replace windowWidth with widthThreshold, identifying the value by chaining jQuery's .parent() twice (essentially it's a more accurate value when getting the width of the parent (x2) element instead of the window).
  2. Added an additional key to child called display. This will be a truncated version of child.name that is used for display, instead of using jQuery's .text() and just rendering using a truncated child.name.
  3. truncPnt becomes characterCount (trying to remember not to abbreviate variables)

The problem now becomes that jQuery is freezing up the browser, until I kill the javascript (if prompted). Firefox may display it, Chrome has yet to not hang, and while I've yet to test in IE, I'd imagine worse than the former.

What can be done to properly get the value of two parents above the main element in question, and truncate child.display so that it will not wrap/extend past the parent div?

UPDATE 2:


I decided to ditch the thought of primarily DOM-based calculations in favor of mathematics, accounting for the width of the parent div, font size, and a ratio of God knows what. I seriously plugged away at a formula until I got something that consistently gave similar results no matter the font size. Media queries do impact the font-size CSS of the string in question, so I needed to account for that or else have some drastic differences in the length of the truncated string between different font-size's:

.directive('truncate', function() {
  return {
    restrict: 'A',
    replace: true,
    // {{child.display}} will be a truncated copy of child.name
    template: '<a class="entity-name" href="{{child.url}}" title="{{child.name}}">{{child.display}}</a>',
    link: function(scope, element, attr) {
      var widthThreshold = $(element).parent().parent().width() * 0.85,
          // get the font-size without the 'px' at the end, what with media queries effecting font
          fontSize = $(element).css('font-size').substring(0, $(element).css('font-size').lastIndexOf('px')),
          // ... Don't ask...
          sizeRatio = 29760/20621,
          characterCount = Math.floor((widthThreshold / fontSize) * sizeRatio);

      scope.$watch('child', function(val) {
        // Truncate it and trim any possible trailing white-space
        var truncatedName = scope.child.name.substring(0, characterCount).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        // Make sure characterCount isn't > the current length when accounting for the '...'
        if (characterCount < scope.child.name.length + 3) {
          scope.child.display = truncatedName + '...';
        }
      });
    }
  }
});

Interestingly enough, I believe I came full circle back to Brandon Tilley's comment regarding modifying the DOM versus modifying a property in the scope. Now that I've changed it to modifying a property, it would probably better serve in a filter? What is typically the deciding factor for whether or not this sort of manipulation should be handled in a filter versus a directive?

By : Scott


Answers
I refer to the documentation:

Directives

Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM.

http://docs.angularjs.org/guide/directive

Filters

Angular filters format data for display to the user. In addition to formatting data, filters can also modify the DOM. This allows filters to handle tasks such as conditionally applying CSS styles to filtered output.

http://docs.angularjs.org/guide/dev_guide.templates.filters

I would use filters only for the purpose of changing the format of data and nothing else. To be honest I believe using a filter for your purpose is appropriate. And as the docs say a filter can modify the DOM I don't see a reason why u should use a directive at all, a filter seems to be what you are looking for. (Apart from the fact that a bug may force you to use a directive)



This video can help you solving your question :)
By: admin