AngularJS指令修改ng-bind和添加省略号

Eri*_*ari 1 angularjs angularjs-directive

我已经制作了一个AngularJS指令来为溢出添加省略号:隐藏文本.它似乎不适用于Firefox,我不相信我已经尽可能地构建它.流程是:

  1. 将指令属性添加到HTML元素
  2. 指令将ng-bind属性读入范围
  3. 指令监视链接功能中ng-bind的更改
  4. 在ng-bind更改时,指令执行一些花哨的计算以确定应该拆分文本和添加省略号的位置(我这里没有包含此代码,只是假设它有效)
  5. Directive将元素的HTML设置为等于此新字符串,而不是触及ng-bind

HTML

<p data-ng-bind="articleText" data-add-ellipsis></p>
Run Code Online (Sandbox Code Playgroud)

指示

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
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

有问题的一行是指令中的最后一行:

 element.html(newText)
Run Code Online (Sandbox Code Playgroud)

我假设应该使用一些模板式方法?我不清楚如何最好地接近答案.谢谢你的帮助.

小智 10

您可以使用过滤器.像这样的东西:

过滤

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

HTML

<p data-ng-bind="articleText | addEllipsis"></p>
Run Code Online (Sandbox Code Playgroud)