Eric Di Bari
Eric Di Bari

Reputation: 3867

AngularJS Directive to Modify ng-bind and Add Ellipsis

I've made an AngularJS directive to add an ellipsis to overflow: hidden text. It doesn't seem to work in Firefox, and I don't believe I've structured it as well as possible. The flow is:

  1. Add directive attribute to HTML element
  2. Directive reads ng-bind attribute into scope
  3. Directive watches for changes to ng-bind in link function
  4. On ng-bind change, directive does some fancy calculations to determine where text should be split and ellipsis added (I've not included this code here, just assume it works)
  5. Directive sets the element's HTML equal to this new string, not touching ng-bind

HTML

<p data-ng-bind="articleText" data-add-ellipsis></p>

DIRECTIVE

app.directive('addEllipsis', function(){
    return {
        restrict    : 'A',
        scope       : {
            ngBind    : '='  // Full-length original string
        },
        link        : function(scope, element, attrs){
            var newValue;

            scope.$watch('ngBind', function () {
                /*
                 *  CODE REMOVED - Build shortened string and set to: newText
                 */

                 element.html(newText);  // - Does not work in Firefox and is probably not best practice
            });
        }
    };
});

The line in question is that last one in the directive:

 element.html(newText)

I'm assuming some template-style approach should be used? I'm unclear how to best approach the answer. Thanks for any help.

Upvotes: 1

Views: 5375

Answers (2)

zs2020
zs2020

Reputation: 54514

If you replace data-ng-bind="articleText" with ng-model="articleText" it should work in both Chrome and Firefox. I don't know why, maybe it is a bug? But it is a quick fix.

If you are interested in the difference, you can take a look at this post. But the behavior being different in different browser is indeed a bit weird.

Upvotes: 0

Brad Gibson
Brad Gibson

Reputation: 101

You could use a filter instead. Something like this:

FILTER

app.filter('addEllipsis', function () {
    return function (input, scope) {
        if (input) {
            // Replace this with the real implementation
            return input.substring(0, 5) + '...';  
        }
    }
});

HTML

<p data-ng-bind="articleText | addEllipsis"></p>

Upvotes: 10

Related Questions