指令:$ observe,类属性更改仅捕获一次 [英] Directive : $observe, class attribute change caught only once
问题描述
我有一条指令可以更改div的样式,并且每次元素的类更改时,$ observe都会通知我.问题在于它在指令创建时发生,而不是在指令创建后发生. 这是代码和小提琴
I have a directive changing the style of a div and would like to be notified by $observe each time the class of the element changes. The problem is that it happens at directive creation but not after. Here is the code and a fiddle
<div ng-app="testObserve">
<div ng-controller="Ctrl2">
<span class="rouge" ng-click="toggleClass()" my-test>Coucou</span>
</div>
</div>
angular.module('testObserve', [])
.controller('Ctrl2', function ($scope) {})
.directive('myTest', function () {
function link(scope, element, attrs) {
scope.toggleClass = function () {
if (element.hasClass('rouge')) {
element.removeClass('rouge');
} else {
element.addClass('rouge');
}
console.log( 'I become ' + element[0].outerHTML );
};
attrs.$observe('class', function (val) {
console.log('class has changed' + val);
debugger;
});
}
return {
link: link
};
});
这是正常行为吗?
好吧,我发现它必须是ng-class而不是html和js代码中的class(在文档中).
Ok I found, it has to be ng-class instead of class both in the html and the js code (it is in the documentation).
固定js位于此处.
所以我改变了一个问题:如果另一个js改变了类而不是ng-class,我该如何观察呢?
So I change a bit the question : if another js changes the class, but not ng-class, how may I observe that ?
要回答有关@js是否在角度范围内的@koolunix问题(是的,unix是kool :)),实际上我想使用角度bootsrap下拉菜单,并在下拉菜单打开或关闭时触发一些操作.
To answer to @koolunix's question (and yes unix is kool :) ) about if js is in the angular scope, actually I want to use angular bootsrap dropdown and trigger something when the drop down opens or closes.
奇怪的是,尽管它是一个有角度的模块,但它使用的是class而不是ng-class.因此,我没有找到一种从外部捕获信息的方法,因为它仅以开放"类的形式出现.
Strangely, although it is an angular module, it uses class instead of ng-class. So I did not find a way to catch that information from the outside as it only appears as the appearance of the 'open' class.
我认为提交的答案有效,但是我仍然需要尝试.
I think the submitted answer works, but I still need to try.
作为解决方法,我复制了ui-bootstrap指令,并在其中添加了我需要的内容.
As a work around I duplicated the ui-bootstrap directive and added what I needed inside.
谢谢!
推荐答案
$observe
用于观察包含插值的属性的值变化.
$observe
is used to observe the value changes of attributes that contain interpolation.
例如:
<span class="{{something}}">Hello</span>
在您的示例中,您可以使用 $ watch 来监视像这样的class属性:
In your example you can use $watch instead to watch for changes on the class attribute like this:
scope.$watch(function() {
return element.attr('class');
}, function(newValue, oldValue) {
if (newValue !== oldValue) { // Values will be equal on initialization
console.log('class has changed to: ' + newValue);
}
});
工作示例: http://plnkr.co/edit/SImhYTkN11eAECC8gDXm?p=preview
这篇关于指令:$ observe,类属性更改仅捕获一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!