Element
<button ud-listener="item.status">{{item.value}}</button>
and I have the following directive
myApp.directive('myDirective', function()
{
return {
restrict: 'A',
link: function(scope, element, attrs)
{
scope.$watch(attrs.myDirective, function(val)
{
if(!isUndefined(val))
{
element.addClass(val);
setTimeout(function(){
element.removeClass(val);
}, 2000);
}
});
}
}
});
What am I trying to do is:
I am receiving json formated datas with socket-io and I am watching the myDirective which holds the value, which is required for add/-removeClass.
At the beginning it works like a charm, the directive adds the class to the element and removes it after 2 sec. without any problem. But few min later it does not add the class to all elements only to few of them.
Is there another way to do it? I only want to addClass to the element and removeClass after 2 seconds.
Most likely it's because either:
You're not referencing JQuery ... or...
Your JQuery reference doesn't come before your angular reference
<script src="/scripts/jquery.js" type="text/javascript"></script>
<script src="/scripts/angular.js" type="text/javascript"></script>
If Angular sees JQuery while it's loading, element
will be a full JQuery object, otherwise it's jqLite.
I noticed a couple things:
setTimeout
instead of $timeout
.When you do this you are executing your code outside of the Angular context so it doesn't know to do a dirty check. Try replacing
setTimeout(function(){
element.removeClass(val);
}, 2000);
with
$timeout(function(){
element.removeClass(val);
}, 2000);
You'll also need to include $timeout
as an argument to the directive factory method.
scope.$watch
instead of attrs.$observe
I'm not sure about the ramifications here but this is how I've always seen it done before.
try:
attrs.$observe('myDirective', function(val){
...
}