AngularJS:动态显示分割文本

时间:2018-11-19 12:15:37

标签: html angularjs

我想显示一个文本,该文本由换行符分隔,并受固定长度限制,该长度不得超过所显示的文本。这是Js代码:

angular.module('app').filter('cut', function () {
  return function (value, max, tail) {
    if (!value) return '';

    max = Number(max);
    if (!max || max === Infinity) return value;

    if (_.sum(value, v => v.length) < max) return value;

    var totalLength = 0;
    var result = [];
    for (var i in value) {
      if (totalLength + value[i].length > max) {
        var partialString = "";
        var splitted = value[i].split('');
        for (var j in splitted) {
          if (totalLength + Number(j) + 1 <= max) {
            partialString += splitted[j];
          }
        }
        result.push(partialString);
        totalLength += partialString.length;
        break;
      }
      else{
        result.push(value[i]);
        totalLength += value[i].length;
      }
    }

    result[result.length - 1] += (tail || ' …')

    return result;
  };
});

angular.module("app").controller("ctrl", ["$scope", function($scope){
    var vm = this;

    $scope.event = { content: "some long string", $limit: 600 };
    vm.splitByLineBreak = function(text) {
      if (text) {
        return text.split("\n");
      }
      return text;
    }
  ]);

和html代码:

<div ng-repeat="elem in ctrl.splitByLineBreak(event.content) | cut: event.$limit  track by $index">
    <span ng-bind-html="elem"></span>
</div>
<div ng-if="event.content.length > 600">
    <a href="" ng-click="event.$limit === Infinity ? event.$limit = 600 : event.$limit = Infinity">
        {{event.$limit === Infinity ? 'Show less': 'Show more'}}
    </a>
</div>

问题在于,如果过滤器剪切了分割字符串的一个元素,则当我单击“显示更多”链接时,剪切的字符串不会更新,也不会完整显示。

0 个答案:

没有答案