Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

javascript - 如何在ng-repeat中使用ng-click?(How to use ng-click in ng-repeat?)

I am new to Angular JS and I am trying to use ng-repeat to generate multiple row in my table, and in each row there should be a button to trigger a function with different parameter(我是Angular JS的新手,正在尝试使用ng-repeat在表中生成多行,并且每行中应有一个按钮来触发具有不同参数的函数)

<div ng-controller="testing">
    <table>
        <thead>
             <tr>
                  <th>col 1</th>
                  <th>col 2</th>
                  <th>button</th>        
             </tr>
        </thead>
        <tbody>
             <tr ng-repeat="item in items">
                 <td>{{ item.prop1 }}</td>
                 <td>{{ item.prop2 }}</td>
                 <td><button ng-click="myFunction(item.id)">Trigger Function</button></td>
             </tr>
        </tody>
    </table>
</div>

This of course doesn't work, as the ng-repeat creates its own scope, while myFunction is defined in the parent scope (ie the testing controller).(这当然是行不通的,因为ng-repeat创建了自己的作用域,而myFunction是在父作用域(即测试控制器)中定义的。)

However, all I can find in Google result is the reason of not working, but lacks a way to fix the problem.(但是,我只能在Google结果中找到无法正常工作的原因,但是却没有解决问题的方法。)

How should I correct my code so that the ng-click works?(我应该如何纠正我的代码,以便ng-click起作用?) Is there a way to define myFunction inside ng-repeat scope or is there a way to tell I want the function in the parent scope?(有没有办法在ng-repeat范围内定义myFunction,还是有办法告诉我要在父范围内的函数?)   ask by cytsunny translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please read the comment under the question.(请阅读问题下方的评论。)

The comments are actually doing better by testing my code and found the code works.(通过测试我的代码,发现这些注释实际上做得更好,并且发现代码有效。) This helps me to realize the problem is elsewhere, which turns out that the function I am calling is mistakenly put under a child controller in the actual code.(这可以帮助我意识到问题出在其他地方,事实证明我正在调用的函数被错误地放置在实际代码中的子控制器下。)

The answers is good but does not solve the problem.(答案是好的,但不能解决问题。)

It worth some reading, but I would prefer not to mark them as correct answer so as not to mislead people.(值得一读,但我宁愿不要将其标记为正确答案,以免误导他人。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...