【发布时间】:2014-05-07 10:49:57
【问题描述】:
我有这个角度的代码:
<span ng-mouseover="item.show_description=true" ng-mouseleave="item.show_description=false" pointer="{x: item.x, y: item.y}">
{{item.label}}
</span>
<div class="description-popup" ng-show="!!item.description && item.show_description"
style="left: {{item.x}}px; top: {{item.y}}px">
<h2>{{item.label}}</h2>
<p>{{item.description}}</p>
<p>{{!!item.description && item.show_description}}</p>
</div>
它正确显示弹出窗口,但如果描述为空或空字符串,弹出窗口仍然显示。在这种情况下,最后一个表达式显示为 false。我在这里做错了什么?或者那里可能有错误。我正在使用 Angular 1.0.6(目前无法升级)。
更新:
我已经创建了 JSFiddle 并且似乎 ng-show 按预期工作,但当我使用指针指令时,使用 mousemove 事件时却没有。该指令的代码如下:
app.directive('pointer', function($parse) {
function objectParser(expr) {
var strip = expr.replace(/\s*\{\s*|\s*\}\s*/g, '');
var pairs = strip.split(/\s*,\s*/);
if (pairs.length) {
var getters = {};
var tmp;
for (var i=pairs.length; i--;) {
tmp = pairs[i].split(/\s*:\s*/);
if (tmp.length != 2) {
throw new Error(expr + " is Invalid Object");
}
getters[tmp[0]] = $parse(tmp[1]);
}
return {
assign: function(context, object) {
for (var key in object) {
if (object.hasOwnProperty(key)) {
if (getters[key]) {
getters[key].assign(context, object[key]);
}
}
}
}
}
}
}
return {
restrict: 'A',
link: function(scope, element, attrs) {
var expr = objectParser(attrs.pointer);
element.mousemove(function(e) {
var offest = element.offset();
scope.$apply(function() {
expr.assign(scope, {
x: e.pageX - offest.left,
y: e.pageY - offest.top
});
});
});
}
};
});
【问题讨论】:
-
在
item.description前面放两个!正常吗? -
@R3tep 这就是在 JS 中将值转换为布尔值的方式。我想确保它获得布尔值。
-
如果去掉
!!,会有同样的行为吗? -
@R3tep 是的,我得到了相同的结果。
-
是否可以创建现场演示(例如使用 jsfiddle)?因为你的代码看起来不错。
标签: javascript angularjs angularjs-directive dom-events