gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 14:55:28 25 4
gpt4 key购买 nike

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

我使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com