【发布时间】:2017-07-14 03:09:12
【问题描述】:
这是一个演示标题中描述的问题的示例:https://plnkr.co/edit/Xn1qgYftc5YHMsrGj0sh?p=preview
指令代码:
.directive('translate', function($compile) {
return {
compile: function(element) {
var html = element.html().split('<br plural="">');
return function(scope, element, attrs) {
function c(h) {
element.html(h);
$compile(element.contents())(scope);
}
if (attrs.translate != '') {
scope.$watch(function() {
return scope.$eval(attrs.translate)
}, function(val, oldval) {
if (val == oldval && html[2] !== undefined) return;
var p = html[2];
html[2] = gettext(html[0], html[1], attrs.add !== undefined ? val + attrs.add : attrs.subtract !== undefined ? val - attrs.subtract : val);
if (p != html[2]) c(html[2]);
});
} else c(gettext(html[0]));
}
}
}
})
所以问题是当我切换回指令以使用 ng-if 显示时 - 它可能不会通过重新编译(?)完全重置,因此会导致行为不端。
如何跟踪指令何时从 DOM 中插入和删除?如果有办法,那么我可以用一个指标来解决这个问题。但一定有更好的办法吧?
【问题讨论】:
-
你能用 ng-show 吗?
-
@mikelt21:在某些情况下,我想优化并改用
ng-if,比如有许多不同的选择,一次只能显示一个,所以这不是解决方案。它存在于ng-show中是有目的的。
标签: javascript angularjs angularjs-directive angularjs-compile angularjs-ng-if