Angular directives - element or attribute?

user1147862 picture user1147862 · May 28, 2014 · Viewed 15.4k times · Source

I'm part of a team with about 6 UI devs, of varying quality and next to no Angular experience. Many are contractors, with little experience with the code base. The app has a very fancy (complicated) UI. It supports IE8+ (soon hopefully IE9+).

We're introducing Angular for a major extension to the app, and I've been asked to write guidelines on the use of Angular for the team.

We'll use directives to create fancy UI elements, all prefixed with "ipwr" to avoid name clashes. I'm trying to decide whether to mandate that devs give their directives the restriction "element" or "attribute". Mandating only one, to avoid chaos and confusion.

My question is: what restrict is better or more popular for directives, "element" or "attribute"? My main concern is ease of use for people with little Angular experience who are new to the application code base, to reduce bugs, copy and paste behaviour, etc.

Answer

ckruszynsky picture ckruszynsky · May 29, 2014

The angular guidance says that you should use the "element" restriction whenever the directive has full control over it's template meaning it has a template that it is rendering out, etc.

For attributes, they suggest to use these only when you are adding "behavior" to an existing element or decorating an existing element.

For example, think of the ng-click directive, this is used a attribute not as a element because the click directive is just adding the click behavior to some element.

Another example would be the ng-repeat directive, it is also used as an attribute not as a element because it is going to repeat the element in which it is being used in.

Now, this guidance is from the angular documentation; however, I don't know necessarily that element vs. attribute is going to give you a "better" approach it's more of a convention.

Now if you have to support older browsers, then you may want to consider using either the comment or class directives.

My personal preference is to just use the attribute restriction; mainly because people that are new to angular get overwhelmed at first when they see the restrict and it's variations of the options that can be used.