我正在尝试使用 ng-class 加载“类”指令。但是当我这样做时,我的指令永远不会加载。该指令是一个多用途指令,我不想为此创建一个孤立的范围。它只会在需要时加载,基于 ng-class 条件,因此不使用属性或元素指令。有没有人试过这样做并成功了?
使用 <div ng-class="someClass {{tooltip: enabled}}"></div>
调用此指令
这里enabled
是一个作用域变量。
app.directive('tooltip', ['$timeout', '$location', '$rootScope', function (timer, $location, $rootScope) {
return {
restrict: 'C',
transclude: true,
link: function (scope, element) {
var printContent = function () {
/* uses the content of .tooltip-content if it is a complex html tooltip,
otherwise
you can use the title attribute for plaintext tooltips
*/
var tooltipContent = $(element).find('.tooltip-content').html();
if (!tooltipContent) {
tooltipContent = $(element).attr('title');
}
$(element).tooltip({
content: tooltipContent,
items: "img, a, span, button, div",
tooltipClass: "tooltip",
position: { my: "left+30 top", at: "right top", collision: "flipfit" },
show: { effect: "fadeIn", duration: "fast" },
hide: { effect: "fadeOut", duration: "fast" },
open: function (event, ui) { $rootScope.tooltipElement = event.target; }
});
};
timer(printContent, 0);
}
};
}]);
最佳答案
有趣的问题。似乎您不想使用 ng-class 指令,因为在添加类后不会重新编译内容。您可能希望创建自己的动态类指令,当值为 true 时实际重新编译:
app.directive('dynamicClass', function($compile) {
return {
scope: {
dynamicClassWhen: '=',
dynamicClass: '='
},
link: function(scope, elt, attrs) {
scope.$watch('dynamicClassWhen', function(val) {
if (val) {
console.log(val);
elt.addClass(scope.dynamicClass);
$compile(elt)(scope);
}
});
}
};
});
您可能需要修改它才能删除类,具体取决于
$compile
对您来说已经足够了,或者如果您需要进一步操作 html,但这似乎是您的正确轨道。我做了一个 fiddle有了这个在行动。希望这可以帮助!
关于angularjs - 使用 ng-class 加载指令时,类指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19230011/