在 AngularJS 中显示更多功能?

Usm*_*bal 3 javascript angularjs angularjs-limitto

我有一份物品清单及其信息。问题是我想显示最多50字符的描述。如果超过这个值我想显示一个show more按钮。单击该按钮后,我想显示全文。我想用过滤器来做到这一点,但我不知道如何实现这一点。

{{jobs.description | limitTo: 2}}{{jobs.description.length>20 ? '...':''}}
Run Code Online (Sandbox Code Playgroud)

我可以<a href="">show more</a>在字符位置写链接吗...

或者还有其他方法可以实现我的目标吗?

Roh*_*dal 6

观察:

  • 您的实施是正确的。问题出在你的 AngularJS 版本上。
  • AngularJS limitTo过滤器从此可用于数组和字符串v1.2.1

工作演示

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {

    // Initial 50 characters will be displayed.
    $scope.strLimit = 50;

    // String
    $scope.jobs = {
      description: "Hi I have a list of items along with their information. The problem is I want to show the description up to 50 letters, but if it exceeds this value I want to show show more button upon clicking it I want to show the full text. I want to do it with filters, but I don't know one could achieve this with my way."
    };

  // Event trigger on click of the Show more button.
   $scope.showMore = function() {
     $scope.strLimit = $scope.jobs.description.length;
   };
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  {{ jobs.description | limitTo:strLimit }}
  <span ng-if="jobs.description.length > 50">
    <button ng-click="showMore()">Show more</button>
  </span>
</div>
Run Code Online (Sandbox Code Playgroud)

Plnkr根据评论更新了show less功能。

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {

    // Initial 50 characters will be displayed.
    $scope.strLimit = 50;

    // String
    $scope.jobs = {
      description: "Hi. I have a list of items along with their information. The problem is I want to show the description up to 50 letters, but if it exceeds this value I want to show show more button upon clicking it I want to show the full text. I want to do it with filters, but I don't know one could achieve this with my way."
    };

  // Event trigger on click of the Show more button.
   $scope.showMore = function() {
     $scope.strLimit = $scope.jobs.description.length;
   };

  // Event trigger on click on the Show less button.
   $scope.showLess = function() {
     $scope.strLimit = 50;
   };
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  {{ jobs.description | limitTo:strLimit }}
  <span ng-if="jobs.description.length > 50 && jobs.description.length != strLimit">
    <button ng-click="showMore()">Show more</button>
  </span>
  <span ng-if="jobs.description.length == strLimit">
    <button ng-click="showLess()">Show less</button>
  </span>
</div>
Run Code Online (Sandbox Code Playgroud)