如何从控制器范围内的函数返回值?



我试图创建一个地图并用角度的标记填充它,并且进行得很好。现在,我试图给$ cope.map从函数返回的映射。我该怎么办?功能当前返回"未定义",为什么?有更好的方法吗?从很长的时间里,我就被困了,我是Angular的新手。你能帮我吗?请?以下是我的代码。

var appa = angular.module('appa',['firebase','uiGmapgoogle-maps']);
appa.controller('mainCtrl', function($firebaseObject,$scope) {
          $scope.coords = function(){
            var ref =  firebase.database().ref();
            var latArray = [];
            var lngArray = [];
            var cenlat;
            var cenlng;
              var marker = [];
            ref.once("value")
            .then(function(snapshot)
            {
            snapshot.forEach(function(child){
              latArray.push(child.child("Lat").val());
              lngArray.push(child.child("Long").val());
              var mark = {
              id: child.child("Id").val(),
              coords: {
              latitude: child.child("Lat").val(),
              longitude: child.child("Long").val()
              },
              options: { title: child.child("Alt").val() }
              };
              marker.push(mark);
            });
               cenlat = (Math.max.apply(Math,latArray)+Math.min.apply(Math,latArray)/2);
               cenlng = (Math.max.apply(Math,lngArray)+Math.min.apply(Math,lngArray)/2);
            });
            $scope.map.moo = cenlat;
          };
          $scope.map = {
            moo: "0",
            center:
            {
                    latitude: $scope.map.moo, longitude: 4 },
             zoom: 2
                  };
                  $scope.coords();
   });

欢迎来到JS的ASYNC关闭世界:)

return ref.once("value")

并在需要的地方hadle

$scope.map = {};
// invoke
$scope.coords().then(function(snapshot){
  // ...
  $scope.map.moo = cenlat;
});

给它一个回调参数

$scope.coords = function(callback){
  ref.once("value").then(callback);
}

$scope.map = {
  // ...
};
// invoke
$scope.coords(function(snapshot){
  // ...
  $scope.map.moo = cenlat;
});

或实际上您的代码:

$scope.map = {};
$scope.coords = function(){
  ref.once("value").then(function(snapshot) {
    // ...
    $scope.map.moo = cenlat;
  }
}

到您的最后一个问题

$scope.coords = function(){
     ref.once("value").then(function(snapshot) {
        // ...
        $scope.map.center.latitude = cenlat;
     }
 }
$scope.map = {
    center: {
        longitude: 4
    },
    zoom: 2
};
$scope.coords()

最新更新