如果满足条件,如何添加CSS类Angular JS [英] How can add a CSS class if a condition is met Angular JS
问题描述
我正在创建一个truncate指令,如果字符超过10个,我将截断文本字符串,然后显示"...".
I'm working on creating a truncate directive and I have the string of text truncating if the characters exceed 10. It will then display the "...".
我的目标是编写一个条件,如果字符少于10个,则将其删除.
My Goal is to write a condition that removes the "..." if the characters are less than 10. Kind of stuck on this and open to suggestions if anyone has any ideas on how I could accomplish this.
这是我的代码:
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>
推荐答案
您可以简单地使用span元素上的> ngHide
指令,条件如下:
You can simply use ngHide
directive on the span
element that contains '...', with the following condition:
ng-hide="input.length <= maxCharacters || !length"
表示如果输入的长度小于或等于maxCharacters
或未应用过滤器,则此元素将被隐藏.
that means that this element is going to be hidden in case the length of input is less or equals maxCharacters
or filter is not applied.
基于代码笔的工作示例:
Working example based on your 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>
这篇关于如果满足条件,如何添加CSS类Angular JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!