【发布时间】:2015-02-27 16:24:08
【问题描述】:
我在指令中使用 DOM 操作时出现了一些意外行为。我有两个图标,想要图标、电话和电子邮件,并希望在悬停时显示它们的内容。这应该很简单,但我在遍历 DOM 以到达子元素时遇到了麻烦。
这是我的指令:
app.directive('contact', function () {
return {
restrict: 'E',
scope: {
email:'@',
phone: '@',
extension: '@'
},
link: function (scope, element, attrs) {
var el = element;
var kids = $(el).children();
var emailChild = $(kids[0]);
var email = emailChild.context.children[0];
element.children().bind('mouseenter', function() {
console.log(this);
console.log(emailChild.context.children[0]);
console.log(email);
});
},
template: '<div class="contact_methods">' +
'<div ng-if="email" class="email" href="#">' +
'<div class="contact_info_email more_info" style="display:none;"><a ng-href="mailto:{{email}}">{{email}}</a></div>' +
'</div> ' +
'<div ng-if="phone" class="phone" href="#"> ' +
'<div class="contact_info_phone more_info">{{phone}} ext.{{extension}}</div>' +
'</div>' +
'</div>'
}
});
这是意外行为:
console.log(this);
console.log(emailChild.context.children[0]);
console.log(email);
这些评估为:
<div class="contact_methods">…</div>
<div ng-if="email" class="email ng-scope" href="#">…</div>
undefined
电子邮件输出未定义;但是,它的内容是上面的那行吗?我也无法像 element.children().children() 那样深入研究它?悬停停止工作。
【问题讨论】:
-
出于某种原因 element.find('.email').bind('mouseenter', function() {console.log('yes'); });不行吗?但是 element.bind('mouseenter', function() {console.log('yes'); });会。
-
@byrdr 你没有 replace true,这意味着你的孩子实际上是模板的根。你为什么不只使用角度事件?
-
由于某种原因 replace:true 有另一个奇怪的效果。 element.children().bind('mouseenter', function() { console.log(this); });不会返回任何东西。
标签: javascript html angularjs dom angularjs-directive