ng-click在ng-repeat内部不起作用 [英] Ng-click doesn't work inside ng-repeat

查看:199
本文介绍了ng-click在ng-repeat内部不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ng-click在ng-repeat内部无效.在外面工作. 我在小提琴放在这里

Ng-click doesn't work from inside ng-repeat. Outside it works. I've put a fiddle here

<div ng-controller="MyCtrl">
 <a ng-click="triggerTitle='This works!'">test</a>
    <h5>Please select trigger event: [{{triggerEvent}}] {{triggerTitle}}</h5>
       <ul class="dropdown-menu">
         <li ng-repeat="e in events">
             <a ng-click="triggerTitle=e.name; triggerEvent = e.action;">{{e.action}} - {{e.name}}</a>
         </li>
       </ul>
</div>

推荐答案

如Ven所述,ng-repeat确实为循环中的每个项目创建了一个子作用域.子作用域确实可以通过原型继承访问父作用域的变量和方法.令人困惑的是,当您进行分配时,它向子作用域添加了一个新变量,而不是在父作用域上更新了属性.在ng-click中,当您进行赋值调用tiggerTitle =e.name时,实际上会将一个名为triggerTitle的新变量添加到子作用域. AngularJS文档在此处称为 JavaScript原型的部分中对此进行了很好的解释.继承.

As Ven mentioned, ng-repeat does create a child scope for each item in the loop. The child scopes do have access to the parent scope's variables and methods through prototypal inheritance. The confusing part is when you make an assignment, it adds a new variable to the child scope rather than updating the property on the parent scope. In ng-click, when you make an assignment call tiggerTitle =e.name, it actually adds a new variable called triggerTitle to the child scope. The AngularJS docs explains this well in the section here called JavaScript Prototypal Inheritance.

那么如何解决这个问题并正确设置模型变量?

一种快速而肮脏的解决方案是像这样使用$parent访问父范围.

A quick and dirty solution is to access the parent scope using $parent like so.

<a ng:click="$parent.triggerTitle=e.name; $parent.triggerEvent = e.action;">...

单击以使用$ parent解决方案查看Fiddle的有效版本.

如果要处理嵌套模板或嵌套ng-repeat,则使用$parent可能会引起问题.更好的解决方案可能是在控制器的作用域中添加一个函数,该函数返回对控制器作用域的引用.如前所述,子作用域可以调用父函数,因此可以引用控制器的作用域.

The use of $parent can cause issues if you are dealing with nested templates or nested ng-repeats. A better solution may be to add a function to the controller's scope which returns a reference to the controller's scope. As already mentioned, the child scopes have access to call the parent functions, and thus can reference the controller's scope.

function MyCtrl($scope) {
    $scope.getMyCtrlScope = function() {
         return $scope;   
    }
 ...

<a ng-click="getMyCtrlScope().triggerTitle=e.name;getMyCtrlScope().triggerEvent = ...

单击以使用更好的方法查看您的Fiddle的有效版本

这篇关于ng-click在ng-repeat内部不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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