I am trying to change the CSS of an element during mouseover using custom directives (just for practice!):
<!DOCTYPE html>
<html ng-app="m1">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body>
<table>
<tr custom-tr>
<td>Hello</td>
</tr>
<tr custom-tr>
<td>Hi</td>
</tr>
<tr custom-tr>
<td>Bye</td>
</tr>
</table>
</body>
<script>
var m1 = angular.module("m1", []);
m1.directive('customTr', function()
{
var d={};
d.restrict = 'A';
var oldStyle = null;
var newStyle = {'color': 'red'};
d.link = function(scope, element, attr)
{
if (!oldStyle)
{
oldStyle = element[0].style;
}
element.bind('mouseenter', function(){
element.css(newStyle);
});
element.bind('mouseleave', function(){
element.css(oldStyle);
});
}
return d;
});
</script>
</html>
The changing behaviour is working, but what I want is to revert the CSS back to what it was originally. For that I am trying to save the CSS state in a variable and then reassigning to this variable later.
But it is not working properly (the last two rows behave as expected but the first row does not change CSS on mouseleave).
Also, an error is being generated:
Uncaught TypeError: Cannot assign to read only property 'length' of object '#<CSSStyleDeclaration>'
Can anyone tell me how to correctly save and reassign the CSS of an element?
ng-styleorng-classinstead?ng-classto very easily switch styles.ctrl.style = 'color:red;'and then in your controller append that usingng-style