为什么指令 ng-href 需要 {{}} 而其他指令不需要? [英] Why does the directive ng-href need {{}} while other directives don't?
问题描述
我只是想知道为什么我需要为 ng-href 添加双花括号而其他一些指令不需要它们?
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>
注意 ng-href
需要大括号而 ng-if
不需要.
Notice that ng-href
needs braces while ng-if
doesn't.
推荐答案
我不太确定你的问题.但我认为您想知道为什么 angular 指令中有不同的语法样式.首先,请看看这篇文章:angular JS中双花括号和单花括号的区别? 答案解释了{{}}
、{}
和不带花括号的区别.
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.
对于您的具体示例,如文档所述:ng-href
需要一个模板(任何可以包含 {{}}
标记的字符串),而 ng-if 需要一个表达式 - 例如您可能不会编写 {{}}
,因为 angular 会对其进行评估.
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.
如果您查看 Angular 源,您会看到 ng-href
使用 attr.$observe
而 ng-if 使用 $scope.$watch
函数.$observe 会在属性值的每次更改时调用.$watch 被调用,当表达式结果为一个新值时.
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>
如您所见,您只需为动态插入的 userId
和 postId
值编写表达式.如果 ng-href
也将使用我们必须编写的 $watch
函数(不要这样做,因为它不起作用 - 它只演示了区别):
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>
这篇关于为什么指令 ng-href 需要 {{}} 而其他指令不需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!