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 - Yii2 Ajax DropDownList 更改 div 的内容

javascript - 管理复杂的 json 响应

javascript - 后网格布局上的随机不同颜色背景

javascript - 显示下一个隐藏的 div 和隐藏当前显示的 div

javascript - 让jqGrid的cb列更宽

php - 使用 css 定位 div 标签

css - 如何在不丢失边框底部的情况下调整 <tr> 的大小

javascript - 日期过滤器格式化 Angularjs

javascript - IE 中的 AngularJS 错误与样式与 ng 样式

javascript - 我应该怎么做才能限制字符数?