【问题标题】:Why does ng-mouseover not work with ng-if为什么 ng-mouseover 不能与 ng-if 一起使用
【发布时间】:2015-09-01 14:24:50
【问题描述】:

我正在尝试在具有“ng-if”的图像上使用“ng-mouseover”指令并且它不起作用但是如果我使用“ng-show”指令它可以工作,每个人都可以告诉我为什么吗?还是 AngularJS 的问题?

在 AngularJS 文档中,我看不到任何关于它的内容:https://docs.angularjs.org/api/ng/directive/ngMouseover

ng-显示

<button ng-show="true" ng-mouseover="countOne = countOne + 1" ng-init="countOne=0">
Increment (when mouse is over)
</button>
Count: {{countOne}}

如果

<button ng-if="true" ng-mouseover="countTwo = countTwo + 1" ng-init="countTwo=0">
Increment (when mouse is over)
</button>
Count: {{countTwo}}

小提琴:http://plnkr.co/edit/Wb6bjyJdHj5qoH7fxGFJ?p=info

【问题讨论】:

    标签: angularjs angularjs-ng-show angularjs-ng-if


    【解决方案1】:

    您观察到的行为是由 ngIf 的工作方式引起的 - from the docs

    请注意,当使用 ng-if 删除元素时,其作用域被破坏 并在元素恢复时创建一个新范围。范围 在 ngIf 中创建的使用 prototypal 从其父作用域继承 遗产。一个重要的含义是如果使用 ngModel 在 ngIf 中绑定到父级中定义的 javascript 原语 范围。在这种情况下,对变量中的任何修改 子作用域将覆盖(隐藏)父作用域中的值。

    这基本上意味着如果您使用ng-if,则需要使用$parent。像这样:

    <button ng-if="true" ng-mouseover="$parent.countTwo = countTwo + 1" ng-init="$parent.countTwo=0">
    

    【讨论】:

      【解决方案2】:

      ng-if 像其他指令一样创建一个子作用域。您的代码需要 $parent 来指向您想要的范围。

      试试这样的:

      <p>
        <button ng-if="true" ng-mouseover="$parent.countTwo = countTwo + 1" ng-init="$parent.countTwo=0">
          Increment (when mouse is over)
        </button>
        Count: {{countTwo}}
      </p>
      

      plunkr

      【讨论】:

        【解决方案3】:

        你正在使用ng-if,所以你必须使用$parent

        工作plunkr

        如果

        <button ng-if="true" ng-mouseover="$parent.countTwo = countTwo + 1" ng-init="$parent.countTwo=0">
        Increment (when mouse is over)
        </button>
        Count: {{countTwo}}
        

        【讨论】:

          【解决方案4】:

          我认为这是因为 $event 超出了该绑定的范围。

          here is an example:
          
          http://plnkr.co/edit/Wb6bjyJdHj5qoH7fxGFJ?p=preview
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-05-04
            • 2017-08-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多