AngularJS Tutorial - Change the DOM in Response to User Actions with custom directive








The following code shows how to change the DOM in Response to User Actions with custom directive.

Example


<!doctype html>
<html ng-app="MyApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
    <script src="http://code.jquery.com/jquery.min.js"></script>
    <script>
var app = angular.module("MyApp", []);
<!--from   w  ww.  j  a v  a  2 s .  c  om-->
app.directive("yourWidget", function() {
  var linkFunction = function(scope, element, attributes) {
    var paragraph = element.children()[0];
    $(paragraph).on("click", function() {
      $(this).css({ "background-color": "red" });
    });
  };

  return {
    restrict: "E",
    link: linkFunction
  };
});    
    </script>
  </head>
  <body>
    <your-widget>
      <p>Click me to see the change</p>
    </your-widget>
  </body>
</html>

The code above is rendered as follows: