我想根据用户单击的按钮更改图标的颜色(假设有一个弹出窗口具有三个按钮,即高、中、低。如果用户单击“高”,它应该变为红色. 中 - 橙色.. 低 - 蓝色.. 我用三个按钮为 popover 做了一个指令。但我无法更新关于按钮单击的 css 类。
html:
<span class="tk-action-s">
<i priority-over class="fa fa-star {{colorChanger}}" ng-class="colorChanger"></i>
</span>
指令:
myApplication.directive('priorityOver', function ($compile) {
var itemsTemplate = "<div class=\"btn-group\"></div><div class=\"btn-group\"><label class=\"btn btn-danger\" ng-model=\"priority\" btn-radio=\"'high'\" ng-click=\"changeColor()\" uncheckable>High</label><label class=\"btn btn-warning\" ng-model=\"priority\" btn-radio=\"'medium'\" uncheckable>Medium</label><label class=\"btn btn-primary\" ng-model=\"priority\" btn-radio=\"'low'\" uncheckable>Low</label></div>";
var getTemplate = function () {
var template = '';
template = itemsTemplate;
return template;
}
return {
restrict: "AC",
transclude: true,
template: "<span ng-transclude></span>",
controller: function($scope, $element, $attrs) {
$scope.colorChanger = 'col';
},
link: function (scope, element, attrs) {
scope.colorChanger = 'col' ;
var popOverContent;
var html = getTemplate();
popOverContent = $compile(html)(scope);
var options = {
content: popOverContent,
placement: "bottom",
html: true,
//title: scope.title
};
$(element).popover(options);
$('body').on('click', function (e) {
$(element).each(function () {
// hide any open popovers when the anywhere else in the body is clicked
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
$(this).popover('hide');
}
});
});
}
};
});
最佳答案
正如nikos在评论中所说,它看起来很复杂。您似乎在混合作用域、指令和模板。你可能想看看 documentation .
无论如何,与此同时这里是一个alternative到你的解决方案。
html:
<div ng-app="example">
<span class="tk-action-s">
<button priority-over class="fa fa-star col"></button>
</span>
<script type="text/ng-template" id="priorityPopover">
<div class="btn-group">
<label class="btn btn-danger" btn-radio="'high'" ng-click="changePriority('high')" uncheckable>High</label>
<label class="btn btn-warning" btn-radio="'medium'" ng-click="changePriority('medium')" uncheckable>Medium</label>
<label class="btn btn-primary" btn-radio="'low'" ng-click="changePriority('low')" uncheckable>Low</label>
</div>
</script>
指令:
angular.module('example', []).directive('priorityOver', function ($compile, $templateCache) {
return {
restrict: "AC",
link: function (scope, element, attrs) {
scope.changePriority = function (priority) {
$(element).removeClass("low medium high");
$(element).addClass(priority);
};
$(element).popover({
content: $compile($templateCache.get('priorityPopover').trim())(scope),
placement: "bottom",
html: true,
trigger: 'focus'
});
}
};
});
请注意模板是如何从指令外部化并使用 $templateCache 服务加载的。也没有更多的嵌入,我们公开了通过范围从按钮添加和删除样式的行为。允许我们访问应用指令的元素。例如,当您想要进行单元测试时也很方便。
关于javascript - 如何更改指令中元素的 css 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27038799/