为什么指令NG-HREF需要{{}},而其他指示没有? [英] Why does the directive ng-href need {{}} while other directives don't?

查看:374
本文介绍了为什么指令NG-HREF需要{{}},而其他指示没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道,为什么我需要加双花括号为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-如果没有。​​

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

推荐答案

我不太清楚你的问题。但我觉得你想知道为什么在角指令语法不同的风格。首先关闭所有,请看看这篇文章:<一href=\"http://stackoverflow.com/questions/17878560/difference-between-double-and-single-curly-brace-in-angular-js\">Difference在角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-如果需要一个前pression - 例如你可以不写 {{}} ,因为角度计算它。

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.

如果你看一下角来源,你会看到, NG-HREF 使用 ATTR。$观察而NG-如果使用 $范围。$看功能。 $观察是caled的属性值的每一个变化。 $表被调用,当前pression结果为新的值。

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.

但为什么这两种不同的方式?我想,有一点是更容易使用和code可读性。现在,你可以写:

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>

正如你所看到的,你的动态插入用户id 帖子ID 值只写一个前pression 。如果 NG-HREF 也将使用我们不得不写的 $观看函数(的不这样做因为它西港岛线无法正常工作 - 它只是表明了区别的):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆