1

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?

7
  • any reason why wouldn't use ng-style or ng-class instead? Commented Aug 22, 2016 at 19:17
  • @Daniel_L For practice of angular directives. Commented Aug 22, 2016 at 19:18
  • you don't have to suffer through parsing css rules. include all the rules you want in your css file and use ng-class to very easily switch styles. Commented Aug 22, 2016 at 19:19
  • I know that there are easier ways to do this, but I want to do in this way only (for learning purpose). Commented Aug 22, 2016 at 19:20
  • ok then why not assign your style declaration in your directive to ctrl.style = 'color:red;' and then in your controller append that using ng-style Commented Aug 22, 2016 at 19:22

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.