Even though you should not manipulate the DOM in an AngularJS application but leave that up to AngularJS itself to do there are certainly places where you will need to interact with it. For example you might want to react to events and do something in reusable manner. Sure you can use the ngClick directive to react to a click but there are cases where you need to react to a click and don't want to repeat the same click handler each time.
The place to add these kind of interactive DOM related code in AngularJS is in a directive and not in a controller. In fact a controller should never be aware of the DOM at all to keep it testable.
In the previous blog post I showed how to use a directive with a template to make our HTML smaller and more reusable, in this blog post I am going to show how you could implement your own version of ngClick. Not that you need one but it's an easy example of how to get started with DOM manipulation from a directive :-)
8 part series:
* Getting started with AngularJS
* Creating an AngularJS Controller
* The AngularJS $scope is not the MVC Model
* Using repeating elements in AngularJS
* Filtering the data in an AngularJS ngRepeat element
* Using the AngularJS FormController to control form submission
* Creating an AngularJS Directive
* Using the DOM in an AngularJS application
Your new post is loading...