Basic Behaviors

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

Bring your directives to life with custom behaviours. This is the recommended way of interacting with the DOM in AngularJS. If you find yourself modifying the DOM inside of your controllers (bad), directive behaviours are your solution (awesome).

John Lindquist: Let's go over creating some basic behaviors, we'll just create another app here. It'll say module, we'll call it behaviorApp, and again, no dependencies. Then we'll create two directives here, one to use the behavior of rolling the mouse over the element, and one for the mouse leaving the element.

Our first directive will be app.directive, we'll call this enter, and then return an object, restrict it to A. One thing I didn't mention is, if you don't put a restrict on there, it actually defaults to A so I can get rid of that. I don't have to use that, I can just say link, and put a function in here.

But another thing I didn't mention is that, because this is such a common use case, if all you're going to do is use the link function, you can actually just, instead of returning this object, you can start over. Let me just start over here, and say app.directive, we'll call it enter, and we'll just return a function now. Instead of returning that object and defining things to that object, I can just return the function, and inside of this function, you've got a few things to work with your element.

I'm going to talk about the first two, a scope and element, and actually we're only going to use the element. Say element bind, mouseenter. That bind syntax should be familiar to anyone who's used jQuery before. On mouseenter, we'll say console.log, "I'm inside of you".

From there, so our directive is named enter, it's going to be an attribute. We'll set up our app, ng-app, call this behaviorApp, and then we'll set up our div with some content, "I'm content". Our directive is just going to be enter.

From here, if we refresh, once we roll over the content you can see that it triggers this, "I'm inside of you", because it's bound to the mouseenter, it's going to do this action, do this behaviour. So, I'm inside, I'm inside.

Then we can duplicate this, and create a leave, and we'll say on mouseleave, "I'm leaving on a jet plane". Then refresh, actually I need to add this to the div, so enter, leave and refresh. You can see inside, leaving, inside, leaving.

Those are basic behaviors and how you set them up, again, it's most common use case, that's why you can do this shorthand without defining that object with the template on it or anything. There you go.