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

标签 javascript html angularjs pug

所以我有一个名为“显示更多”的按钮,一旦达到列表的最大数量,它就会增加列表中的项目数量我想更改为一个名为“显示较少”的按钮,它将列表恢复到它的默认值。

我使用 ng-if 来确定要显示的按钮,并使用 ng-click 来确定操作。当同时使用它们时,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,没有动画而且速度更快。

这是显示更多按钮的 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 和子作用域继承的常见问题。

您正在对原始值进行数据绑定(bind),而 ng-if 正在创建一个子作用域。当您的 ng-click 指令更改“feedLimit”的值时,您实际上是在子作用域上创建一个新的“feedLimit”属性,但 ng-if 指令绑定(bind)到父作用域的“feedLimit”。

解决方案是避免绑定(bind)到原始值。相反,请确保通过绑定(bind)到对象来使用点表示法。

代替

<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

关于javascript - 使用 ng-if 时 ng-click 停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25656979/

相关文章:

javascript - 像这样初始化 jQuery 有什么好处?

javascript - 仅在单击按钮后运行 JavaScript/AJAX

javascript - 如何避免在单个对象中切换多个条件?

javascript - 如何使用 ng-repeat 过滤 AngularJS 中的多个值?

javascript - Google柱形图隐藏了值为零的数据的注释

javascript - 从 nodejs 运行 tomcat

javascript - Kendo UI 编辑器上传和缩略图 Url 事件

html - 在 Div 中将文本和图像彼此相邻放置 - CSS

javascript - Microsoft Edge 浏览器和打印

javascript - Knockout.js 仅在值更改时启用保存