我想将图标的颜色改为用户点击的按钮(比如有一个弹出按钮,它有三个按钮,即高,中,低。如果用户点击“高”,它应该变为红色中等 - 橙色......低 - 蓝色.. 我用三个按钮为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');
}
});
});
}
};
});
答案 0 :(得分:1)
正如尼科斯的评论所说,它看起来相当复杂。您似乎在混合范围,指令和模板。您可能需要查看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服务加载的。也没有更多的转换,我们公开了通过范围从按钮添加和删除样式的行为。允许我们访问应用该指令的元素。当您想要进行单元测试时也很方便。