javascript – ng-click在使用ng-if时停止工作

前端之家收集整理的这篇文章主要介绍了javascript – ng-click在使用ng-if时停止工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我有一个名为“show more”的按钮,一旦达到我希望更改为名为“show less”的按钮的列表的最大数量,它将增加列表中的项目数量,从而使列表恢复到其默认值.

我使用ng-if来确定要显示的按钮和ng-单击以确定操作.当它们一起使用时,ng-click停止工作,当我点击时没有任何反应.

这里是我用jade编写的html,FeedLimit是列表中显示的项目数.

button.btn.btn-primary.btn-block.btn-sm.btn-outline(type='button')(ng-if= "FeedLimit < notifications.all.length",ng-click="FeedLimit = FeedLimit + 4")
  span(translate) Show More
button.btn.btn-primary.btn-block.btn-sm.btn-outline(type='button')(ng-if= "FeedLimit >= notifications.all.length",ng-click="FeedLimit = 4")
  span(translate) Show Less

我尝试过使用ng-show和ng-hide,它们工作正常,但最好使用ng-if,没有动画,而且速度更快.

这是show more按钮的html输出

<button type="button" ng-if="FeedLimit < notifications.all.length" ng-click="FeedLimit = FeedLimit + 4" class="btn btn-primary btn-block btn-sm btn-outline ng-scope" style=""><span class="ng-scope">Show More</span></button>

解决方法

我认为你遇到了angularjs和子范围继承的常见问题.

您是数据绑定到原始值,ng-if正在创建子范围.当你的ng-click指令改变’FeedLimit’的值时,你实际上是在子范围上创建一个新的’FeedLimit’属性,但ng-if指令绑定到父范围的’FeedLimit’.

解决方案是避免绑定到原始值.而是确保通过绑定到对象来使用点符号.

代替

<button ng-if="FeedLimit < notifications.all.length" ng-click="FeedLimit = FeedLimit + 4">

尝试类似的东西

<button ng-if="someObj.FeedLimit < notifications.all.length" ng-click="someObj.FeedLimit = someObj.FeedLimit + 4">

这是对最新情况的更详细解释.

https://github.com/angular/angular.js/wiki/Understanding-Scopes

Scope inheritance is normally straightforward,and you often don’t
even need to know it is happening… until you try 2-way data binding
(i.e.,form elements,ng-model) to a primitive (e.g.,number,string,
boolean) defined on the parent scope from inside the child scope. It
doesn’t work the way most people expect it should work. What happens
is that the child scope gets its own property that hides/shadows the
parent property of the same name. This is not something AngularJS is
doing – this is how JavaScript prototypal inheritance works. New
AngularJS developers often do not realize that ng-repeat,ng-switch,
ng-view and ng-include all create new child scopes,so the problem
often shows up when these directives are involved. (See this example
for a quick illustration of the problem.)

This issue with primitives can be easily avoided by following the “best practice” of always have a ‘.’ in your ng-models

原文链接:/js/150137.html

猜你在找的JavaScript相关文章