javascript AngularJS ng-click 在 <li> 标签中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27216459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS ng-click not working in <li> tag
提问by Alex Jolig
I'm making a pagination list image using AngularJS
. ng-click
doesn't work when I use it in <li>
tag or even on <a>
tag in it. But it's working fine in <button>
tag.
我正在使用AngularJS
. ng-click
当我在<li>
标签中甚至在其中的<a>
标签上使用它时不起作用。但它在<button>
标签中工作正常。
<div ng-controller="sampleCtrl" ng-app="myApp" data-ng-init="currentpage=1">
<h2>{{currentpage}}</h2>
<ul>
<li data-ng-repeat="image in images[currentpage-1]">
<img src='{{ image.img }}' width="150px" height="88px"/>
</li>
</ul>
<ul class="pagination">
<li data-ng-repeat="i in [1,2,3,4,5]" title="Page {{i}}">
<a href="#" data-ng-click="currentpage = currentpage + 1">{{i}}</a>
</li>
</ul>
<button data-ng-click="currentpage = currentpage + 1">Click me!</button>
</div>
Anyone knows what's the problem?
有谁知道是什么问题?
BTW, I tried this answer, but it's not working.
顺便说一句,我试过这个答案,但它不起作用。
回答by Shomz
It's because ng-repeat
creates a new scope for each repeated element. And when you're doing currentpage = currentpage + 1
, you're most probably creating a new variable inside a child scope.
这是因为ng-repeat
为每个重复的元素创建了一个新的作用域。当你在做的时候currentpage = currentpage + 1
,你很可能是在子作用域内创建一个新变量。
Check your scopes. The solutions is usually something as simple as $parent.currentpage = $parent.currentpage + 1
(to address the currentpage
variable in the parent scope, the sampleCtrl
scope) if you don't want to rewrite the whole thing.
检查你的范围。如果您不想重写整个事情,解决方案通常很简单$parent.currentpage = $parent.currentpage + 1
(解决currentpage
父作用域中的变量,即sampleCtrl
作用域)。
Another solution would be creating a function to increase the page number, that way you won't be creating any new child scope variables, but would inherit the increase function from the controller:
另一种解决方案是创建一个增加页码的函数,这样您就不会创建任何新的子作用域变量,而是从控制器继承增加函数:
<a href="#" data-ng-click="increasePage()">{{i}}</a>
And in your controller something like this:
在你的控制器中是这样的:
$scope.increasePage = function() {
currentpage++;
}