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”。



<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">


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上找到一个类似的问题:


javascript - Connect-busboy : When piping file to write steam, 文件为空或不正确,具体取决于类型

css - 我如何设计带有 div 和 span 的网站(而不是表格标签)

html - 如何基于最小主题自定义主题中的答案帖子?

javascript - HTML语句中的if语句

AngularJS Accordion 展开全部 全部折叠

javascript - 更好地理解 javascript 中的回调函数

javascript - 使用javascript,Cushy CMS更改textContent

javascript - 当我只需要构建时,为什么 yarn 会安装开发依赖项?

javascript - 处理列中的所有字符串

javascript - AngularJS:通过字段名称获取数组值