我有一个简单的模板,如下所示:

      <ul ng-repeat="email in emails">
      <br>Email ID {{email.EmailsID}} <br>
       Unread {{email.Unread}}
       <ul>


问题是我需要通过两个调用来获取数据:一个API中的EmailsID列表和另一个API中的每个UnreadEmailsID值。任何想法如何使这项工作?我在下面尝试了一些方法,可以获取EmailsID,但是我不知道如何将其与syncAPI中每个emailsId的未读值合并。目前,我已经在API URL中将emailsId值硬编码为9,如以下http://local.app.com:8080/imap/syncAPI?emailsId=9所示

var crmApp = angular.module('crmApp', []);

crmApp.controller('EmailsCtrl', function($scope, $http) {
  $http.get('http://local.app.com:8080/emailsAPI', {withCredentials: true}).success(function(data) {
 var index;
for (index = 0; index < data.length; ++index) {
$http.get('http://local.app.com:8080/messages/imap/syncAPI?emailsId='+data.EmailsID+'&mailbox=inbox', {withCredentials: true}).success(function(unreadD) {

 data[index].unread = unreadD;
   $scope.emails = data;
      });
});


我是angularjs和javascript的新手

最佳答案

问题是您要迭代一系列异步回调,其中每个回调在被调用时肯定会引用index = emails.length。即您的所有回调都将引用$scope.emails[data.length] = unreadD

可以使用angular.forEach()代替使用for循环作为迭代器。

var crmApp = angular.module('crmApp', []);

crmApp.controller('EmailsCtrl', function($scope, $http) {
  $http.get('http://local.app.com:8080/emailsAPI', {withCredentials: true})
    .success(function(emails) {
       $scope.emails = emails;
       angular.forEach(emails, function(email) {
          $http.get('http://local.app.com:8080/imap/syncAPI?emailsId=' + email.EmailsID + '&mailbox=inbox', {withCredentials: true}).success(function(unreadD) {
            email.Unread = unreadD;
          });
       });
    });
});

关于javascript - 如何在模板中绑定(bind)两个变量(angularjs),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24965723/

10-12 02:51