gpt4 book ai didi

javascript - Angular JS 指令 - 模板、编译或链接?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:34:44 25 4
gpt4 key购买 nike

我想创建一个 Angular JS 指令来检查字符串的长度,如果它太长而无法使用过滤器缩短它,并在鼠标悬停时显示一个 Angular-UI 弹出窗口。

我应该在指令中的什么位置放置功能以使其正常工作(链接、模板或编译)?

View :

<div myapp-shorten="project">{{project.Description}}</div>

到目前为止,这是我对该指令的第一次尝试:

angular.module('myapp.directives', [])
.directive('myappShorten', function () {

function link(scope, element, attrs) {

var outputText = "";

if (myappShorten.Description.length > 20) {
outputText += "<div popover='{{myappShorten.Description}}' popover-trigger='mouseenter'>" +
"{{myappShorten.Description | cut:true:20:' ...'}}</div>";
} else {
outputText += "<div>{{myappShorten.Description}}</div>";
}

element.text(outputText);
}

return {
link: link,
scope: {
myappShorten: "="
}
};

});

最佳答案

首先,您可以更改过滤器,使其在不需要时不会更改字符串

其次,因为您只需要过滤器和弹出窗口 - 模板就足够了。

 angular.module('myapp.directives', [])
.directive('myappShorten', function () {

return {
scope: { data : '=myappShorten',
template:"<div popover='{{data.Description}}' popover-trigger='mouseenter'>" +
"{{ data.Description | cut:true:20:' ...' }}</div>"
}
})

或者,您可以结合使用 ng-showng-hide

 app.directive('shorten', function () {
return {
restrict: 'A'
, scope : {
shorten : '=',
thestring: '='
}
, template: "<div ng-show='sCtrl.isLong()' tooltip='{{ sCtrl.str }}'>{{ sCtrl.short() }}</div>"+
"<div ng-hide='sCtrl.isLong()'>{{ sCtrl.str }}</div>"

, controllerAs: 'sCtrl'
, controller: function ($scope) {
this.str = $scope.shorten || ''
this.length = $scope.thestring || 20

this.isLong = function() {
return this.str.length > this.length
}

this.short = function() {
if ( this.str.length > this.length) {
return this.str.substring(0,this.length) + '...'
}
}
}
}
})

第三个选项是在 myappShrten.Description 上实际使用 compile 和 $watch,但这对我来说似乎有点矫枉过正。

关于javascript - Angular JS 指令 - 模板、编译或链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23770882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com