我想知道是否可以通过 ngRepeat 模板内的 Angular 方法调用返回数据库结果。为了澄清这里是我的模板:
<div class="article-right" ng-repeat="localNews in allLocalNews | limitTo:5">
<div class="article-title">
<p>
On {{localNews.dte | date}}
<a>Number of comment: {{getNumberOfComment(localNews.id)}} </a>
</p>
</div>
这是我的 Controller ,在我的 Controller 中,我有一个方法,它接受 ngRepeat 中结果的每个 id 值,以从数据库中获取评论数量
$scope.getNumberOfComment = function(id){
var cObj = {id:id}; //get a news number of comments
return $http.post("shared/search/getNumberOfComment.cln.php",cObj).success(function(response){
if(response != "failed"){
return response;
}
}).error(function (response, status) {
console.log(response);
});
}
此脚本使我的浏览器在进入循环时卡住。任何帮助将不胜感激。
最佳答案
它可能会循环,因为每个摘要周期都会重新调用以获取信息。 您最好拥有一个为每个项目填充的变量,并在每个元素上调用类似 ng-init 的内容,该变量只会被调用一次来初始化您的项目变量。 这有道理吗?
例如
<div class="article-right" ng-repeat="localNews in allLocalNews | limitTo:5">
<div class="article-title">
<p>
On {{localNews.dte | date}}
<a ng-init=getNumberOfComment(localNews.id, localNews)>Number of comment: {{localNews.myVar}} </a>
</p>
</div>
$scope.getNumberOfComment = function(id, localNews){
var cObj = {id:id}; //get a news number of comments
return $http.post("shared/search/getNumberOfComment.cln.php",cObj).success(function(response){
if(response === "passed"){
localNews.myVar = response;
}
}).error(function (response, status) {
console.log(response);
});
}
关于javascript - 如何通过Angular方法返回数据库结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45866629/