gpt4 book ai didi

javascript - 将属性值传递给指令模板

转载 作者:行者123 更新时间:2023-12-02 16:13:09 25 4
gpt4 key购买 nike

最终目标

我们希望有一个属性可以添加到任何与上下文帮助对话框相关联的元素中,这样当我们将鼠标光标悬停在元素上时,就会弹出一个窗口来显示帮助信息。这是我们想要做的示例:

<label help-info="This is what will be displayed in the help dialog">Help Example</label>

不过,我在正确地将字符串参数传递给模板时遇到了一些问题。

这是我尝试过的:

索引.html

<html ng-app="myApp">
<head>
<script data-require="angular.js@*" data-semver="2.0.0-alpha.20" src="https://code.angularjs.org/2.0.0-alpha.20/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="HelpInfoDirective.js"></script>
</head>

<body ng-controller="myCtrl">
<div help-info="test"></div>
</body>
</html>

HelpInfoTemplate.html

<div>
{{'this is a' + _attrs.help-info}}
</div>

HelpInfoDirective.js

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

app.directive('helpInfo', function(){
return{
restrict: 'A',
scope: true,
templateUrl: function(_elements, _attrs){
'HelpInfoTemplate.html'
}
// link: function(_scope, _elements, _attrs){
// _scope.helpAttr = _attrs.help-info;
// }
}
});
})();

首先,我尝试使用链接参数来传递参数,但它不起作用,因此我尝试将模板放入函数中,但没有成功。

将属性值传递给模板的正确方法是什么?

此外,一旦我们获得了该值,我们如何修改返回的模板,以便我们可以使用 ng-show 来显示弹出窗口(我们最终会将其放入模式中)。我愿意接受建议。

链接到Plunk

最佳答案

将属性值传递给模板的正确方法是什么?

将值绑定(bind)到模板

值通过编译过程绑定(bind)到模板。您可以使用 $compile 服务并提供模板需要绑定(bind)到的范围来编译指令的链接函数中的代码:

app.directive('helpInfo', function($compile){
return{
restrict: 'A',
scope: {title : '@'},
link: function(scope, el){
var newElement = $compile('<div>{{title}}</div>')(scope);
el.hover(function(){
el.after(newElement);
});

el.mouseout(function(){
el.nextAll().first().remove();
});

}
}
});

定义指令的范围

您需要为指令设置一个独立的范围,并指定属性的名称,您将在其中定义弹出窗口中显示的文本。我在本例中使用“标题”作为属性。

然后您可以像这样使用该指令:

<div help-info title="I am a title">Click me</div>

演示

这是一个 Plunker,它展示了这一点的实际效果。

http://plnkr.co/edit/VwdHC3l9b3qJ4PF6cGV1?p=preview

此外,一旦我们有了值,我们如何修改返回的模板,以便我们可以使用 ng-show 来显示弹出窗口

在我提供的示例中,我使用 jQuery href() 和 mouseout() 事件来响应用户将鼠标悬停在 DOM 元素上或远离 DOM 元素。如果你想更进一步,这里是 a tutorial显示如何将弹出窗口或警报放入服务中。

关于javascript - 将属性值传递给指令模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29933274/

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