Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS best practice to inherit scope in directive

From Directives documentation it says to inherit scope in this two ways:

@ or @attr - bind a local scope property to the value of DOM attribute. The result is always a string since DOM attributes are strings. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localName:'@myAttr' }, then widget scope property localName will reflect the interpolated value of hello {{name}}. As the name attribute changes so will the localName property on the widget scope. The name is read from the parent scope (not component scope).

= or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localModel:'=myAttr' }, then widget scope property localModel will reflect the value of parentModel on the parent scope. Any changes to parentModel will be reflected in localModel and any changes in localModel will reflect in parentModel.

Considering that i want to pass elementId, which is just an id, I can pass it through =elementId or @elementId.

Now which one of the two is considered best practice? If I use the @ and therefore the attribute, it will take the value from the DOM which is slower than taking directly the value?

Am I correct? Any suggestions?

like image 274
piggyback Avatar asked Feb 18 '23 14:02

piggyback


1 Answers

  • If the directive needs to change the value, use = to get bi-directional binding.
  • If you want to make it clear to other people reading your code that you are only using one-way binding, use @.
  • If you need access to the value in the linking function synchronously, use = (see note about @ and $observe's asynchronous behavior here).

For your case, @ seems best. (An example of how you would use the directive and elementID in an HTML element would be helpful though.)

I have no idea which is slower/faster.

See also What is the difference between '@' and '=' in directive scope in AngularJS?

like image 135
Mark Rajcok Avatar answered Feb 20 '23 02:02

Mark Rajcok