【问题标题】:How can add a CSS class if a condition is met Angular JS如果满足条件Angular JS如何添加CSS类
【发布时间】:2018-02-21 09:44:15
【问题描述】:

我正在创建一个截断指令,如果字符超过 10 个,我会截断文本字符串。然后它将显示“...”。

我的目标是编写一个条件,如果字符少于 10 个,则删除“...”。如果有人对我如何实现这一点有任何想法,我会坚持这一点并接受建议。

这是我的代码:

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

// Controller
app.controller('mainCtrl', function($scope) {
  $scope.text = "John Doe Blah blah";
});

// Directive
app.directive('truncate', function() {
  function link(scope, element, attrs){
    scope.truncate = function(str){
      if(str.length > 10) {
        return 'truncate'
      } else{
        return 'notruncate'
      }
    }
  }
  
  // Write a condition to check if the username is < 10 characters to hide the ellipse
  
  
  return{
    restrict: 'A',
      scope: {
        input: '=',
        maxCharacters: '=',
        href: '=',
        isShowMore: '='
      },
    template: '<h4 ng-init="limit=true;length=maxCharacters">{{input | limitTo: length}}<a ng-attr-href="#" ng-click="limit=!limit;length=limit?maxCharacters: \'\'">{{isShowMore?"Show More":"..."}}</a></h4>',
    link: link
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<html ng-app='myApp'>
  <body ng-controller='mainCtrl'>
    <div href='true' input='text' is-show-more='false' max-characters='10' truncate=''></div>
  </body>
</html>

【问题讨论】:

标签: javascript angularjs haml truncate


【解决方案1】:

您可以简单地在包含“...”的span 元素上使用ngHide 指令,条件如下:

ng-hide="input.length <= maxCharacters || !length" 

这意味着如果输入的长度小于或等于maxCharacters 或未应用过滤器,则该元素将被隐藏。

基于您的 codepen 的工作示例:

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

// Controller
app.controller('mainCtrl', function($scope) {
    $scope.text = "John Doe Blah blah";
});

// Directive
app.directive('truncate', function() {
    // Write a condition to check if the username is < 10 characters to hide the ellipse

    return {
        restrict: 'A',
        scope: {
            input: '=',
            maxCharacters: '=',
            href: '=',
            isShowMore: '='
        },
        template: '<h4 ng-init="limit=true;length=maxCharacters">{{input | limitTo: length}}<a ng-attr-href="#" ng-click="limit=!limit;length=limit?maxCharacters: \'\'" ng-hide="input.length <= maxCharacters || !length" >{{isShowMore?"Show More":"..."}}</a></h4>'
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<html ng-app='myApp'>
  <body ng-controller='mainCtrl'>
    <div href='true' input='text' is-show-more='false' max-characters='10' truncate=''></div>
  </body>
</html>

【讨论】:

  • 非常感谢!!! ? 这正是我所需要的。我也理解它背后的逻辑
  • @ThomasBrushel 如果它解决了您的问题,您可以接受答案。
  • 嘿,我有一个简单的问题,因为您似乎对 Angular js 非常了解。我正在尝试在此代码笔 codepen.io/Brushel/pen/pWbzqM 上做同样的事情,我采取了一些或不同的方法。我已经构建了截断功能,但是,我无法根据一定数量的字符来隐藏和显示它。另外,我试图弄清楚如何使用 %atom-heading{text: 'whatever'} 而不将 truncatorBindings 附加到 HTML 标记。如果您打开控制台,您会看到我收到一条错误消息,提示 TypeError: Cannot set property 'text' of undefined
【解决方案2】:

你可以试试这样的。

"use strict";

function exampleController($scope) {
  $scope.example = "Yeyuh im so long, where does it end?!";
}

function truncate() {
  return {
    restrict: "A",
    scope: {
      text: "=",
      length: "="
    },
    link: function($scope, $element, $attrs) {
      var elm = $element[0];
      $scope.$watch("text", function(newText, oldText) {
        if (elm.classList.value.indexOf("notruncate") > -1) {
          elm.classList.remove("notruncate");
        }
        if (newText.length > $scope.length) {
          elm.className = "truncate";
        }
        if (newText.length < $scope.length) {
          if (elm.classList.value.indexOf("truncate") > -1) {
            elm.classList.remove("truncate");
          }
          elm.className = "notruncate";
        }
      });
    }
  };
}

angular
  .module("example", [])
  .controller("exampleController", exampleController)
  .directive("truncate", truncate);
.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.notruncate {
  white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container-fluid" ng-app="example">
  <div class="container" ng-controller="exampleController">
    <input type="text" ng-model="example" truncate text="example" length="10">
  </div>
</div>

【讨论】:

    【解决方案3】:

    Angular 有一个 ngClass 指令,它将根据表达式的评估文本应用一个类。只需编写一个根据字符串长度返回不同类的函数,然后在 ngClass 中调用它。

    ngClass 的文档:https://docs.angularjs.org/api/ng/directive/ngClass

    示例代码sn-p

    var app = angular.module('myApp', []);
    
    // Controller
    app.controller('mainCtrl', function($scope) {
          $scope.text = "John Doe Blah blah";
          
          $scope.truncate = function(str){
            if (str.length > 10) {
             return 'truncate'
            } else {
             return 'notruncate'
            }
          }
    });
    .truncate {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .notruncate {
      white-space: nowrap;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <html ng-app="myApp">
    <div ng-controller="mainCtrl" ng-class="truncate(text)" style="width: 40px">{{text}}</div>
    </html>

    【讨论】:

    • 这就是我被卡住的原因。过去两周我只在 AngularJs 中工作,哈哈。我已经显示了椭圆。如果少于 10 个字符,我只需要说一些 {{isShowMore?"Show More":"..."}} 来不显示更多。
    • 我修改了我的代码。要进行测试,只需更改 $scope.text 的值。它会做你想做的事,不需要复杂的布尔逻辑(或自定义指令)。您必须根据要截断的文本量正确调整 div 的大小,但这应该不难。
    • 谢谢!我真的很喜欢这个解决方案,如果这不是用于大规模应用程序,它会起作用。这需要是一个指令,以便它可以在站点周围的多个地方使用。我需要在指令中构建它,然后在组件中构建它。
    • 您可以将此功能包装在指令中。只需将函数和 ng-class 内容作为包装指令的一部分。该类将是全局的,因为它是 angular 1.x,但它仍然可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多