Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the directive ng-href need {{}} while other directives don't?

I am just wondering why I need to add double curly braces for ng-href while some of the other directives don't need them?

<a ng-href="{{myScopeVar}}" ng-if="myScopeVar">link</a> 

Notice that ng-href needs braces while ng-if doesn't.

like image 244
TheBakker Avatar asked Jan 23 '14 09:01

TheBakker


People also ask

What is Ng-href directive?

The ng-href directive overrides the original href attribute of an <a> element. The ng-href directive should be used instead of href if you have AngularJS code inside the href value. The ng-href directive makes sure the link is not broken even if the user clicks the link before AngularJS has evaluated the code.

What does link function do in a directive?

link function is basically used to manipulate the DOM( Document Object Model ) element using custom directive. link option in custom directive registers DOM listener and also update the DOM.

Which directive is used to start an AngularJS application?

ng-app: The ng-app Directive in AngularJS is used to define the root element of an AngularJS application. This directive automatically initializes the AngularJS application on page load. It can be used to load various modules in AngularJS Application.


1 Answers

I am not quite sure about your question. But i think your are wondering why there are different syntax styles in angular directives. First off all, please have a look at this post: Difference between double and single curly brace in angular JS? The answer explains the difference between {{}}, {} and no braces.

For your concrete examples, as in the documentation stated: ng-href requires a template (any string which can contain {{}} markup), while ng-if requires an expression - e.g. you may not write {{}}, because angular evaluates it.

If you have a look at the angular sources you will see, that ng-href uses attr.$observe while ng-if uses the $scope.$watch function. $observe is caled on every change of the attribute value. $watch is called, when the expression results to a new value.

But why these two different ways? I think one point is easier usage and code readability. Right now you can write:

<a ng-href="http://yourdomain.com/users/{{userId}}/post/{{postId}}">title</a> 

As you can see, you only write an expression for dynamically inserted userId and postId values. If ng-href would also use the $watch function we had to write (don't do this because it wil not work - it only demonstrates the difference):

<a ng-href="'http://yourdomain.com/users/'+userId+'/post'+postId">title</a> 
like image 162
michael Avatar answered Oct 25 '22 12:10

michael