【问题标题】:Why does the directive ng-href need {{}} while other directives don't?为什么指令 ng-href 需要 {{}} 而其他指令不需要?
【发布时间】:2014-01-23 09:07:31
【问题描述】:

我只是想知道为什么我需要为 ng-href 添加双花括号,而其他一些指令不需要它们?

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

注意ng-href 需要大括号,而ng-if 不需要。

【问题讨论】:

  • 假设您想动态构建 url,例如:ng-href="#/foobar/{{barfoo}}"。此外,您可能还想阅读manual 中的描述以获得更长的解释。

标签: angularjs angularjs-directive


【解决方案1】:

我不太确定你的问题。但我认为您想知道为什么角度指令中有不同的语法样式。首先,请看这篇帖子:Difference between double and single curly brace in angular JS? 答案解释了{{}}{} 和无括号的区别。

对于您的具体示例,如文档所述:ng-href 需要一个模板(任何可以包含 {{}} 标记的字符串),而 ng-if 需要一个表达式 - 例如你可能不会写{{}},因为 Angular 会评估它。

如果您查看角度源,您会看到 ng-href 使用 attr.$observe 而 ng-if 使用 $scope.$watch 函数。 $observe 在属性值的每次更改时都会被调用。当表达式产生新值时调用 $watch。

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

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

如您所见,您只为动态插入的userIdpostId 值编写表达式。如果ng-href 也将使用我们必须编写的$watch 函数(不要这样做,因为它不起作用 - 它只是展示了不同之处):

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

【讨论】:

  • 我可以使用ng-href 的函数输出,比如ng-href="{{my_function()}}"吗?
  • @ShellFish 是的,你可以
【解决方案2】:

即使我使用 ng-href data-ng-href 它也会抛出验证错误。 我使用&lt;link rel="stylesheet" data-ng-href="{{datas}}" href="/"&gt; 来传递验证错误。

希望对某人有所帮助

【讨论】:

    猜你喜欢
    • 2014-03-30
    • 2013-01-28
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    相关资源
    最近更新 更多