【发布时间】:2015-02-18 15:31:42
【问题描述】:
背景: 我正在开发一个显示文章列表的 Angular 应用程序。该列表可以通过各种设置进行修改。一种这样的设置是这些文章的来源。将来源视为新闻机构:一篇文章来自特定来源:
因此,当用户点击“来源”链接时,应该会出现一个下拉菜单,其中包含来源列表。用户可以选择这些来源的任意组合。还有一个“全选”和“全部清除”按钮可以选择所有源或全部取消选择:
问题: 所以每次用户选择或取消选择一个来源时,都应该向服务器发送一个http请求,并且应该更新文章列表。
我的问题是,我不确定如何调用将发送 http 请求的函数(在下面的代码 sn-ps 中,它被称为 updateArticleList())。
1) 如果我将函数绑定到ng-click 并将其设置在label 标签上:
<ul>
<li ng-repeat="source in sources">
<label ng-click="updateArticleList()">
<input type="checkbox" ng-model="source.selected">
{{source.title}}
</label>
</li>
</ul>
然后单击标签会触发该功能两次(一次用于label,显然一次用于input)。不好。
2) 如果我将函数绑定到input 标签上的ng-change:
<ul>
<li ng-repeat="source in sources">
<label>
<input type="checkbox" ng-model="source.selected"
ng-change="updateArticleList()">
{{source.title}}
</label>
</li>
</ul>
然后,一旦我单击“全选”或“清除”按钮,这将更改所有复选框的状态并发送大量 http 请求。也不好。
现在,我正在尝试使用setTimeout 来解决这个问题,以过滤对函数的一连串调用,就像这样(通过 ng-click 调用函数的示例):
var requestAllowed = true;
var debounceRequests = function(){
requestAllowed = false;
setTimeout(function(){
requestAllowed = true;
}, 5);
};
scope.updateArticleList = function(){
if (requestAllowed === true){
// prevent the second call to the function from ng-click
debounceRequests();
// also, give time for the input to register ng-click on the label
setTimeout(function(){
// finally, send an http request
getArticles();
}, 5);
}
};
但这看起来很脏。
那么,我的问题是,在这种情况下发出 http 请求的好方法是什么?
最好不要使用额外的 js 库。
===================
更新:
这是“全选”触发的功能:
scope.selectAllSources = function(){
scope.sources.forEach(function(source){
source.selected = true;
});
scope.updateArticleList();
};
【问题讨论】:
-
好问题:很好的目标和问题
-
@NewDev 是对的,你能发布你的 selectAll 代码吗?
-
@azangru,您需要只提交更改的来源,还是只重新提交所有选定的来源(即使只选择了 1 个额外的来源)?
-
@NewDev:我还不太确定。目前,我正在重新提交所有来源列表,指出哪些被选中(
selected=true),哪些未被选中。一定是浪费带宽:-(
标签: javascript angularjs