How can Angular be used to dynamically show or hide an element based on its height?

Is there a way in Angular to display a "Read More" link once the height of a paragraph reaches 200px? I'm looking for an elegant solution.

Here are my elements:

<section class="mynotes" ng-if="MyController.mynotes">
<p ng-bind="MyController.mynotes" ng-class="{'showMore': more, 'showLess': !more}"></p>
<section ng-click="MyOtherController.togglearrow($event)">
      <i class="down-arrow"></i>
      <span ng-click="more = !more">{{more ? 'Less' : 'More'}}</span>
</section>

Any suggestions on how to hide the arrow and Less/More text based on the paragraph's height?

Answer ā„–1

Introducing a new directive designed for the show less feature - simple and configurable.

.directive('moreless', function($timeout){
  //Default options, default height of 200
  var defOption = {
    height:200
  };

  return {
    restrict:'EA',
    transclude:true, //transclusion enabled
    scope:{}, //scoped to isolate since this adds functions on scope
    template:'<div class="showless"><div ng-transclude class="content" ng-style="style"></div><section class="trigger" ng-if="showSection"> \
      <i class="down-arrow"></i> \
      <span ng-click="toggleMore()">{{{true:"More", false:"Less"}[more]}}</span> \
</section></div>',
    link:function(scope, elm, attrs){
      var origHeight,
          //Construct the options from default options and override by any thing specified
          options = angular.extend({}, angular.copy(defOption), scope.$eval(attrs.options));

        //Initialize
        initialize();

        function initialize(){
          scope.toggleMore = toggleMore;
          scope.toggleSection = toggleSection;
          //Do not show showless section initially 
          scope.toggleSection(false);
          //Wait for one digest cycle to complete and intialize showless componenet
          $timeout(_initShowLess);
        }

        function _initShowLess(){
         //Set initial height and get the height
          origHeight = elm.find('.content').height();
          scope.style = {height:origHeight};
          //compare the height to allowed height and togglesection and set showmore accordingly
          if(origHeight > options.height){
            scope.toggleSection(true);
            scope.style.height = options.height;
            scope.toggleMore();
          }
        }

        function toggleMore(){
           expandCollapse(scope.more);
           scope.more = !scope.more;
         }

         function toggleSection(show){
            scope.showSection = show;
         }

         function expandCollapse(expand){
           var height = expand ? origHeight : options.height;
           scope.style.height = height;
         }

     }
  }

});

The default setting is a height of 200, but you can configure it using the options attribute like this:

<moreless options="{height:300}">
  <p ng-bind="mynotes2"></p>
</moreless>

Check out the Demo

Inline Demo'

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

app.directive('moreless', function($timeout) {

  var defOption = {
    height: 200
  };

  var defOffset = 10;

  return {
    restrict: 'EA',
    transclude: true,
    scope: {},
    template: '<div class="showless"><div ng-transclude class="content" ng-style="style"></div><section class="trigger" ng-if="showSection"> \
      <i class="down-arrow"></i> \
      <span ng-click="toggleMore()">{{{true:"More", false:"Less"}[more]}}</span> \
</section></div>',
    link: function(scope, elm, attrs) {
      var origHeight,
        options = angular.extend({}, angular.copy(defOption), scope.$eval(attrs.options));

      initialize();


      function initialize() {
        scope.toggleMore = toggleMore;
        scope.toggleSection = toggleSection;
        scope.toggleSection(false);
        $timeout(_initShowLess);
      }

      function _initShowLess() {

        origHeight = elm.find('.content').height();
        scope.style = {
          height: origHeight
        };
        if (origHeight > options.height) {
          scope.toggleSection(true);
          scope.style.height = options.height;
          scope.toggleMore();
        }
      }

      function toggleMore() {
        expandCollapse(scope.more);
        scope.more = !scope.more;
      }

      function toggleSection(show) {
        scope.showSection = show;
      }

      function expandCollapse(expand) {
        var height = expand ? origHeight : options.height;
        scope.style.height = height;
      }

    }
  }

}).controller('MainCtrl', function($scope) {
  $scope.mynotes = 'Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.';

  $scope.mynotes2 = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
})
/* Put your css in here */

.showless {
  position: relative;
}
.showless .content {
  overflow: hidden;
  transition: all linear 0.5s;
  -webkit-transition: all linear 0.5s;
}
.showless .trigger {
  background: #cdcdcd;
  display: inline-block;
}
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link data-require="bootstrap-css@*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8d9d6dfcdd4d9ca96d2cbf889968b96c0">[email protected]</a>" src="https://code.angularjs.org/1.3.10/angular.js" data-semver="1.3.10"></script>
    
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
  <div>
    <moreless>
      <p ng-bind="mynotes"></p>
    </moreless>
   </div> 
   <div>
    <moreless options="{height:100}">
      <p ng-bind="mynotes"></p>
    </moreless>
    </div> 
       <div>
    <moreless options="{height:300}">
      <p ng-bind="mynotes2"></p>
    </moreless>
    </div> 
  </body>

</html>

Answer ā„–2

I came up with the following directive on the spot, but it should give you a good idea.

angular..directive('setMore',function(){
     return {
        restrict: 'A',
        link: function($scope,$el,$attr) {
            $scope.$watch(function() {
                 return $el.height();
                 },function(height) {
                   $scope.more = height > ~~$attr['setMore'];
                 }
            });
        }
     };
});

This is how you can implement it.

<p set-more="100" ng-bind="MyController.mynotes" ng-class="{'showMore': more, 'showLess': !more}"></p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary to delay until the entire page finishes loading in Selenium 3?

public boolean CheckPageLoadStatus(){ final ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(final WebDriver driver) { return ((JavascriptExecutor) driver).executeScr ...

Node.js based simplistic static HTML web server

I'm looking to create a basic server for serving local HTML and JS files while working on development projects. I attempted to use a node app with express to respond with the page based on the URL, but unfortunately had no success. Here's my cod ...

css center arrow-aligned underline text

Trying to emphasize my text with an additional arrow centered on the line is proving to be a challenge. When attempting this, the text does not align in the center of the page. .souligne { line-height: 17px; padding-bottom: 15px; text-transform: u ...

Exploring the depths of nested image objects using the map method in ReactJS

I successfully mapped through and destructured this object, but I'm struggling to access the image within the same map. I believe I may need to map through it separately, but I'm uncertain. Here is the object: { "attributes": { ...

Identifying Oversized Files on Safari Mobile: A Guide to Detecting Ignored Large Files in

Mobile browsers such as Safari have a tendency to ignore large files when passed in through the <input type="file">. For example, testing with a 10mb image file results in no trigger of any events - no change, no error, nothing. The user action is si ...

Prevent clicks from triggering on dynamically loaded ajax content within a DIV

I am seeking help on how to prevent click events from being triggered on dynamically loaded content within a specific DIV element. <div id="left_column"> <div class="menu">------</div> <div class="menu">------</div> ...

New method for obliterating a controller with the usage of the as and this structure

Is there a different approach to destroy a controller when using the 'as' syntax and binding values on the controller, or should I still rely on the scope? For example, if a controller is declared in the dom using the 'as' syntax: < ...

Python Ordering menu items for the Pelican restaurant

In response to jcollado's advice on this thread, I have set up my menu as per his instructions. However, I am facing difficulty adding the active CSS to the active item. DISPLAY_PAGES_ON_MENU = False DISPLAY_CATEGORIES_ON_MENU = False MENUITEMS = ( ( ...

What are the steps needed to establish a distinct data scope in AngularJS along with the application of filters?

Iā€™m currently practicing my skills in AngularJS and I have been experimenting with creating reusable components. At this stage, I have successfully created a component using the directive method. However, I now have some doubts that I need clarification ...

Utilizing Javascript for altering HTML elements

It seems this issue is quite puzzling and I believe another perspective could be beneficial in identifying the problem. Despite my efforts, I am unable to understand why the "Energy Calculator" does not return a value when submitted, whereas the "Battery C ...

Get rid of the strange border on the material dialog

I am struggling with the Angular material 6 dialog component as it is displaying a strange border. I have attempted to remove it using the code below, without success. Interestingly, when I apply the style inline in the browser, it works fine. Any suggesti ...

Dynamic class/interface in Typescript (using Angular)

Is there a way to achieve intellisense for an object created with a dynamic class by passing parameters? Here is the code snippet: Main: let ita: any = new DynamicClass('ITA'); let deu: any = new DynamicClass('DEU'); The DynamicClass ...

regarding unfamiliar functions in code and their mysterious purposes

My journey learning Vue.js has been going well, but I've hit a roadblock. Can someone explain the meaning of _. in the following code snippet? ...

Pagination of AJAX result on the client side using jQuery

My issue revolves around pagination in AJAX. I want to avoid overwhelming my search result page with a long list of returned HTML, so I need to split it into smaller sections. The Ajax code I am currently using is: $.ajax({ url: "getflightlist.php?pa ...

What are some creative ways to reveal a concealed card through animation?

I have a collection of MUI cards where one card remains hidden until the others are expanded. My goal is to add animation to the hidden card so it doesn't abruptly appear. Below is the styling and logic for achieving this: ** Styling ** const useStyl ...

Sending POST Requests with Next.js Version 14

How can I send a POST request using axios in Next.js 14, I prefer axios but fetch is also okay. I have been getting an AxiosError: Network Error when I try to use axios and TypeError: fetch failed when using fetch. However, it works fine with Postman. I ...

retrieve information using Python in JavaScript

I am in the process of developing a website using Python, Javascript (JQuery), and AJAX. While I know how to initiate a Python script with Ajax, I am unsure of how to send data back to Javascript from Python. For instance, if there is an error in a form s ...

Creating a unique WooCommerce product category dropdown shortcode for your website

I am having trouble implementing a WooCommerce categories dropdown shortcode. Although I can see the drop-down menu, selecting a category does not seem to trigger any action. Shortcode: [product_categories_dropdown orderby="title" count="0" hierarchical=" ...

Tracking the advancement of synchronous XMLHttpRequest requests

Within the client-side environment, there exists a File-Dropzone utilizing the HTML5 File-API which allows users to drop multiple files for uploading to the server. Each file triggers the creation of a new XMLHttpRequest Object that asynchronously transfer ...

How can I achieve a floating effect for a div element that is contained within another element?

I have a container located within the body of my webpage. This container has margins on the left and right, as well as a specified width. Inside this container, there is a div element that extends beyond the boundaries of the container to cover the entire ...