How to create read more/less toggle using Directive?

Today now in this post i want to show you How to create read more/less toggle using Directive? Sometimes we may need to make show read more or read less functionality in our AngularJS application. Here we will make read more by using AngularJS Directive.

So, now in this example i am going to give you a full example of read more text example. Here I will used “dd-text-collapse” Directive for the after some text it will be return “…” OR “(more)” etc that as you want. We can easily customize this Directive. We can also make the toggle read more and read less by using this Directive.

At First, we can see the bellow code of just Directive, i will give you the bellow code of Directive, we can also use direct in our AngularJS application. So let’s see in bellow:

Directive:
app.directive('ddTextCollapse', ['$compile', function($compile) {


  return {
      restrict: 'A',
      scope: true,
      link: function(scope, element, attrs) {


          /* start collapsed */
          scope.collapsed = false;


          /* create the function to toggle the collapse */
          scope.toggle = function() {
              scope.collapsed = !scope.collapsed;
          };


          /* wait for changes on the text */
          attrs.$observe('ddTextCollapseText', function(text) {


              /* get the length from the attributes */
              var maxLength = scope.$eval(attrs.ddTextCollapseMaxLength);


              if (text.length > maxLength) {
                  /* split the text in two parts, the first always showing */
                  var firstPart = String(text).substring(0, maxLength);
                  var secondPart = String(text).substring(maxLength, text.length);


                  /* create some new html elements to hold the separate info */
                  var firstSpan = $compile('<span>' + firstPart + '</span>')(scope);
                  var secondSpan = $compile('<span ng-if="collapsed">' + secondPart + '</span>')(scope);
                  var moreIndicatorSpan = $compile('<span ng-if="!collapsed">... </span>')(scope);
                  var lineBreak = $compile('<br ng-if="collapsed">')(scope);
                  var toggleButton = $compile('<span class="collapse-text-toggle" ng-click="toggle()">{{collapsed ? "(less)" : "(more)"}}</span>')(scope);


                  /* remove the current contents of the element
                   and add the new ones we created */
                  element.empty();
                  element.append(firstSpan);
                  element.append(secondSpan);
                  element.append(moreIndicatorSpan);
                  element.append(lineBreak);
                  element.append(toggleButton);
              }
              else {
                  element.empty();
                  element.append(text);
              }
          });
      }
  };
}]);

Ok good, now here i will make a full example of read more or read less toggle by using above directive. So let’s see and also we can see the demo.

index.html
<!DOCTYPE html>
<html>
<head>
	<title>angularjs read more example</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
        <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
        <style type="text/css">
         .collapse-text-toggle{
           font-weight: bold;
         }
       </style>
</head>
<body>


<div ng-app="mainApp" ng-controller="myController" id="mainController" class="container">
    <p dd-text-collapse dd-text-collapse-max-length="230" dd-text-collapse-text="{{ longText }}"></p>
</div>


<script type="text/javascript">


  var app = angular.module("mainApp", []);


  app.controller('myController', function($scope, $timeout) {
      $scope.longText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";


  });


  app.directive('ddTextCollapse', ['$compile', function($compile) {


      return {
          restrict: 'A',
          scope: true,
          link: function(scope, element, attrs) {


              /* start collapsed */
              scope.collapsed = false;


              /* create the function to toggle the collapse */
              scope.toggle = function() {
                  scope.collapsed = !scope.collapsed;
              };


              /* wait for changes on the text */
              attrs.$observe('ddTextCollapseText', function(text) {


                  /* get the length from the attributes */
                  var maxLength = scope.$eval(attrs.ddTextCollapseMaxLength);


                  if (text.length > maxLength) {
                      /* split the text in two parts, the first always showing */
                      var firstPart = String(text).substring(0, maxLength);
                      var secondPart = String(text).substring(maxLength, text.length);


                      /* create some new html elements to hold the separate info */
                      var firstSpan = $compile('<span>' + firstPart + '</span>')(scope);
                      var secondSpan = $compile('<span ng-if="collapsed">' + secondPart + '</span>')(scope);
                      var moreIndicatorSpan = $compile('<span ng-if="!collapsed">... </span>')(scope);
                      var lineBreak = $compile('<br ng-if="collapsed">')(scope);
                      var toggleButton = $compile('<span class="collapse-text-toggle" ng-click="toggle()">{{collapsed ? "(less)" : "(more)"}}</span>')(scope);


                      /* remove the current contents of the element
                       and add the new ones we created */
                      element.empty();
                      element.append(firstSpan);
                      element.append(secondSpan);
                      element.append(moreIndicatorSpan);
                      element.append(lineBreak);
                      element.append(toggleButton);
                  }
                  else {
                      element.empty();
                      element.append(text);
                  }
              });
          }
      };
  }]);
</script>
</body>
</html>

Read Also: Laravel Import Export Excel & Csv from Database

I hope it will help you. Also you can follow us on Facebook

Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.