Meteor Angular&请求 - 如何绑定?

时间:2016-01-12 19:45:11

标签: javascript angularjs node.js meteor angularjs-scope

我正在尝试完成脚本的最后一个阶段,即显示响应。我有一个Meteor方法,通过基本身份验证从Zendesk的API请求一个对象。我的客户端部分中的Meteor.call()调用此方法。我可以记录响应,但无法将其绑定并显示。

这是我的js:

if (Meteor.isClient) {

    // This code only runs on the client
    angular.module('equationKPIs', ['angular-meteor']);

    angular.module('equationKPIs').controller('EquationKPICtrl', ['$scope',
        function ($scope) {

            Meteor.call("zendeskUnsolvedTickets", function (error, results) {
                var json = JSON.parse(results);
                $scope.metrics = [{
                    'name': 'Unsolved Tickets',
                    'value': json.view_count.pretty
                }];
                console.log($scope.metrics);
            });

        }]);
}

if (Meteor.isServer) {
    Meteor.methods({
        zendeskUnsolvedTickets: function () {
            var request = Meteor.npmRequire('request'),
                username = '',
                password = '',
                url = 'https://equationconsulting.zendesk.com/api/v2/views/',
                auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');

            var options = {
                method: 'GET',
                url: url,
                headers: {
                    'Authorization': auth
                }
            };

            var tickets = Async.runSync(function (done) {
                options.url = url + '32396347/count.json';
                request(options, function (error, response, body) {
                    if (error) throw new Error(error);
                    done(null, body);
                });
            });

            return tickets.result;
        }
    });
}

这是我的HTML:

<div class="container"
     ng-app="equationKPIs"
     ng-controller="EquationKPICtrl">

    <div ng-repeat="metric in metrics">
        <h4>{{metric.name}}</h4>
        <h2>{{metric.value}}</h2>
    </div>

</div>

我尝试了几次js迭代,例如:

$scope.metrics = Meteor.call("zendeskUnsolvedTickets", function (error, results) {
            var json = JSON.parse(results);
            var response = [{
                'name': 'Unsolved Tickets',
                'value': json.view_count.pretty
            }];
            return response;
        });

对我做错的任何见解?

1 个答案:

答案 0 :(得分:1)

你需要调用$scope.$apply()因为你在Angular的上下文之外分配$scope(在ajax回调中)

Meteor.call("zendeskUnsolvedTickets", function (error, results) {
  var json = JSON.parse(results);
  $scope.metrics = [{
    'name': 'Unsolved Tickets',
    'value': json.view_count.pretty
  }];
  console.log($scope.metrics);
  $scope.$apply(); // this here
});

更多here