如何绑定模板中的两个变量(angularjs)

时间:2014-07-25 23:03:32

标签: javascript angularjs

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

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

问题是我需要在两个调用中获取数据:来自API的EmailsID列表和来自其他API的每个Unread的{​​{1}}值。知道如何使这项工作?我已尝试过以下内容,我可以抓取EmailsID,但我不知道如何将其与EmailsID中每封电子邮件的未读值合并。目前,我已在API网址中将emailsId值硬编码为9,如下所示syncAPI

http://local.app.com:8080/imap/syncAPI?emailsId=9

我是angularjs和javascript的新手

2 个答案:

答案 0 :(得分:1)

听起来您希望第一次拨打emailsAPI时使用syncAPI第二次来电syncAPI。为了达到这个目的,请在emailsAPI的成功回调中调用var crmApp = angular.module('crmApp', []); crmApp.controller('EmailsCtrl', function($scope, $http) { var getReadStatus = function(emails) { $scope.emails=emails; for(var i = 0; i < emails.length; i++) { $http.get('http://local.app.com:8080/imap/syncAPI?emailsId=' + emails[i].EmailsID + '&mailbox=inbox', {withCredentials: true}).success(function(unreadD) { $scope.emails[i].Unread = unreadD; }); } } $http.get('http://local.app.com:8080/emailsAPI', {withCredentials:true}).success(function(data) { getReadStatus(data); }); } ,如下所示:

getReadStatus

这里的$scope.emails函数会将从第一个API调用中收到的所有电子邮件分配给与之前相同的变量(EmailsID),然后它将遍历每个电子邮件对象,并使用{{ 1}}属性来调用第二个API。最后,它会向每个Unread对象添加一个名为email的属性,允许从模板中正确访问它。

答案 1 :(得分:1)

问题是你正在迭代一系列异步回调,其中每个回调在被调用时肯定会引用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;
          });
       });
    });
});
相关问题