Angular指令不在视图中呈现范围值

时间:2016-01-04 01:47:48

标签: angularjs angularjs-directive angular-promise angular-services

我的指令使用一个返回promise的服务,我需要在模板中显示范围属性geoZip,geoCity和geoState。

问题是这些范围变量没有显示在模板中,我只看到逗号。

我该怎么做才能让它显示范围变量?

这是我的指令代码:

  .directive('cityStateZip', function() {
      return {
        restrict: 'A',
        transclude: true,
        scope: {
          zip: '=',
        },
        template: '<p>{{geoCity}}, {{geoState}} {{geoZip}}</p>',
        controller: ['$scope', 'GeolocationService', function ($scope, GeolocationService) {
          GeolocationService.geocode($scope.zip).then(function(result) {
            if (result) {
              console.log(result);
              $scope.geoZip = result['address_components'][0]['long_name'];
              $scope.geoCity = result['address_components'][1]['long_name'];
              $scope.geoState = result['address_components'][2]['short_name'];
            }
          });
        }]
      };
    })

.service('GeolocationService', ['underscore', '$q', function (underscore, $q) {
  var gs = {};

  gs.geocode = function(address) {
    var geocoder = new google.maps.Geocoder();
    var deferred = $q.defer();
    geocoder.geocode( { "address": address }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
        return deferred.resolve(underscore.first(results));
      }
      return deferred.reject();
    });
    return deferred.promise;
  }

  return gs;
}]);

1 个答案:

答案 0 :(得分:1)

我发现我必须使用$ timeout服务才能使其正常工作:

indexPathForCell

如果有最好的选择(不使用$ timeout),请告诉我,谢谢!