ng-class 不会在自定义指令上触发 [英] ng-class will not trigger on custom directive
问题描述
我目前正在为 AngularJS 开发一个幻灯片菜单指令.javascript 包含三种类型的指令:针对每种类型的滑动菜单的指令(为简洁起见,我只包括左侧滑动菜单),一个用于屏幕其余部分的包装指令,asmWrapper,以及一个控制按钮指令,asmControl.目前,所有这些指令都使用服务 asmService 进行通信.
I am currently developing a slide menu directive for AngularJS. The javascript consists of three types of directives: the directives for each type of sliding menu (for brevity's sake I only included the left sliding menu), one wrapper directive for the rest of the screen, asmWrapper, and one control button directive, asmControl. Currently, all of these directives are using a service, asmService to communicate.
当用户单击 asmControl 时,该指令的控制器调用 asmService 上的一个方法,该方法确定已触发哪个菜单并在 $rootScope 上发出asmEvent".asmSlidingMenu 的控制器将捕获该事件并更新其范围内的活动变量,但 DOM 元素的 CSS 类保持不变.
When the user clicks an asmControl, that directive's controller calls a method on asmService that determines which menu has been triggered and emits an 'asmEvent' on the $rootScope. asmSlidingMenu's controller will catch that event and update the active variable in its scope, but the DOM element's CSS class remains unchanged.
我假设没有设置 ng-class.我该如何解决这个问题?
I assume the ng-class is not being set. How do I fix this?
我在下面包含了 asmSlidingMenu 指令的代码.要查看更完整的示例,请查看我制作的 Plunker.
I have included the code for the asmSlidingMenu directive below. To see a more complete example, view the Plunker I made.
slideMenu.directive('asmSlideLeft', ['$rootScope', 'asmService',
function($rootScope, asmService) {
return {
restrict: 'AEC'
, scope: {}
, controller: function($scope) {
$rootScope.$on('asmEvent', function(event, prop) {
console.log('Intercepted: ' + asmService.asmStates.slideLeft.active);
$scope.active = asmService.asmStates.slideLeft.active;
});
}
, compile: function(element, attrs) {
attrs.$set('class', 'asm asm-horizontal asm-left');
attrs.$set('data-ng-class', '{"asm-left-open: active"}');
return {
pre: function preLink(scope, iElement, iAttrs) {}
, post: function postLink(scope, iElement, iAttrs) {}
}
}
}
}]);
推荐答案
首先 active
是在一个隔离范围内,所以 ng-class
无法访问它.
First of all active
is in an isolate scope, so ng-class
has no access to it.
其次,也是更重要的是,ng-class
被添加在元素的指令已经被angular收集到之后.为时已晚.
Secondly, and more importantly, ng-class
is added after the directives of the element have been collected by angular. It's too late.
如果您有自己的指令,就没有理由使用 ng-class
.
There's no reason to use ng-class
if you have your own directive.
slideMenu.directive('asmSlideLeft', ['$rootScope', 'asmService',
function($rootScope, asmService) {
return {
restrict: 'AEC'
...
link: function(scope, element) {
element.addClass('asm asm-horizontal asm-left');
$rootScope.$on('asmEvent', function() {
if (asmService.asmStates.slideLeft.active) {
element.addClass('asm-left-open');
}
else {
element.removeClass('asm-left-open');
}
...
这篇关于ng-class 不会在自定义指令上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!