angularjs - 使用 ng-show/hide 时使用 {{}} 与不使用有什么区别

标签 angularjs ng-show

当我尝试自动显示/隐藏时,我发现如果我在属性值表达式中使用 {{}},DOM 初始状态是正确的,但是当我更新模型时, View 尚未更新,“ng-hide”类尚未添加到 DOM,即使属性的值已正确更新为“false”。不正确的 DOM 看起来像这样:

    <p class="grey-text" ng-show="false">no data</p>

但是如果我不使用 {{}},该类可以正确更新。

最佳答案

ng-show 指令(以及大多数指令,包括自定义指令)接受表达式作为参数。

{{ }} 运算符是 Interpolation Markup 。计算插值运算符内的表达式,并输出文本。无法保证此插值将在指令评估数据之前完成。

•There is no guarantee that it works for every directive, because interpolation itself is a directive. If another directive accesses attribute data before interpolation has run, it will get the raw interpolation markup and not data.

这也是多余的,因为该指令已经被设计为在计算结果之前获取表达式并对其执行插值。如果插值发生在指令之前,结果将类似于:

  1. 插入{{myVar}}并返回结果。
  2. 将结果 'false' 写入 DOM。
  3. 指令从 DOM 读取 'false'
  4. 指令插入'false',返回false

相反,您想要更自然的流程:

  1. 指令从 DOM 读取 myvar
  2. 指令插入 myvar,返回 false

一些进一步的说明:

所有这些插值和评估都发生在单个 $digest 周期中。插入和更新 DOM 不会改变表达式的值,只会改变它的显示方式。因此,插值不会触发 $watch 或新的 $digest,并且如果指令错过了以一种或另一种形式看到值,它们就无法知道。因此,指令必须接受原始表达式并自行执行插值以保证准确的结果。

关于angularjs - 使用 ng-show/hide 时使用 {{}} 与不使用有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34734904/

相关文章:

javascript - 在 Angular : are the compile function's pre and post methods the same as link's pre and post

javascript - Angular Directive(指令)模板未加载

javascript - 交替 ng 重复

javascript - 基于字符串数组的 AngularJS 过滤器?

angularjs - 如何在 AngularJS 中使用 ng-repeat 创建嵌套结构

javascript - 如何做快速响应设计的细节

javascript - 简单的 orderBy 过滤器在 AngularJs 中不起作用

javascript - 如何使用 ng-show 和 ng-click 使移动菜单 Angular 化?

javascript - 为 ng-show 和 ng-class 评估空数组时的结果不一致

css - 如何使用 css 或 ngAnimate 在两个 ngShow 消息之间交叉淡入淡出