Directive Restrictions

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

By default AngularJS directives can be used with elements, attributes, classes, and comments. Many times we want to restrict it to one or more of those to control how a directive will be used. This lesson digs into how and why to use Directive restrictions.

John Lindquist: While it's cool to create a custom element in like this one, it's actually more common to do things like create custom attributes. Now these attributes are going to add things like behaviors. You set up an attribute using the restrict A, for A is attribute, B is element. Then you provide a linking function, and this linking function is going to be where you put whatever the behavior is.

I'm going to just write alert and say I'm working. From here, instead of having Superman as an element, we would do this with Superman as an attribute.

OK, refresh this, you see we get an alert saying I am working. The other places you can put this, with this restriction, is C is for class, so if I try to...now, you'll see nothing happens. I tried to refresh there. That means I just need to say class = Superman. Refresh and I'm working, then the other one which I never really see anyone use but I'll show you anyway, is M for comment.

The C is already taken for class so M is for comment. This looks something like...you create a regular comment, then you write the word directive, then you follow by this, refresh.

So you could really make it if you dated all the comments. Typically, I think it's best to add behaviors to attributes. You could do Superman, then add another, stack another attribute on top of him and say Flash, create another directive...say, Flash, attribute and say, I am working faster...I am working...

I am working faster, I'm working stronger and then, Superman and Flash, hit refresh. See, I'm working stronger and I'm working faster. So there you go, that's more of the idea of what those restrictions are. Again, E is for element, A is attribute, C is for class, M is for comment. The attributes are going to be the main ones as far as adding behaviors that get used most.