AngularJS/JS-how 通过服务器返回值转换工厂中的硬编码值

AngularJS/JS-how to convert hard coded value in factory by server returned value

我正在尝试实施在“http://plnkr.co/edit/zsh2Bt7jBl1Z2mKKqlwa?p=preview”上给出的解决方案,它按预期工作(具有硬编码的用户详细信息)但是现在当我尝试通过服务器响应替换硬编码值时,我做不到 - 请帮忙

 var wmapp = angular
    .module('distance', [ 'wmapp.factory_restaurants', 'greatCircles' ])

    // RESTAURANTLIST CONTROLLER
    .controller(
            'restaurantlistController',
            function($scope, $rootScope, restaurantsFactory, position,
                    GreatCircle) {
                "use strict";
                $scope.restaurantList = restaurantsFactory.getRestaurants(); 
    // call
                // to
                // restaurantfactory
                $scope.position = position;

                $scope.distanceTo = function(restaurant) {
                    var distance = GreatCircle.distance(restaurant.long,
                            restaurant.lat, position.longitude,
                            position.latitude)
                    restaurant.distance = distance;
                    distance = distance.toFixed(1);
                    return distance;
                };
                $scope.totalDisplayed = 2; // implementing a load more
                // capability
                $scope.loadMore = function() {
                    $scope.totalDisplayed += 20;
                };
            })

    .factory(
            'position',
            function($rootScope) {

                console.log('building position')

                var position = {};

                // 1ST / AUTO GEOLOCATION OF USER
                // displays a popup to indicate current user location -
                // (disabled)
                // onSuccess Callback - This method accepts a Position
                // object, which contains the current GPS coordinates
                var onSuccess = function(position2) {

                    console.log(position2.coords.latitude)
                    console.log(position2.coords.longitude)

                    //alert("latitude and longitude------"
                        //  + position2.coords.latitude + "----------"
                            //+ position2.coords.longitude);

                      position.latitude = "26.805273";
                        position.longitude = "83.355463";

                    //position.latitude = position2.coords.latitude;
                    //position.longitude = position2.coords.longitude;

                    $rootScope.$digest()
                };

                function onError(error) { // onError Callback receives a
                    // PositionError object
                    alert('code: ' + error.code + '\n' + 'message: '
                            + error.message + '\n');
                }

                navigator.geolocation
                        .getCurrentPosition(onSuccess, onError);

                return position;

            })

  angular
    .module('wmapp.factory_restaurants', [ 'greatCircles' ])

    .factory(
            'restaurantsFactory',
            function() {
                "use strict";
                var factory = {
                    Restaurants : [
                            {
                                Name : '11111111111',
                                venueType : 'Electrician ',
                                subCuisine : 'Fan',
                                subsubCuisine : 'Greesing, Bnding',
                                address : 'abc',
                                city : 'test',
                                country : 'xxx',
                                countryCode : 'kk',
                                lat : 36.805273,
                                long : 73.355463,
                            },
                            {
                                Name : '222222222',
                                venueType : 'Electrician ',
                                subCuisine : 'Fan',
                                subsubCuisine : 'Greesing, Bnding',
                                address : 'hii',
                                city : 'xyz',
                                country : 'abc',
                                countryCode : 'oo',
                                lat : 85.320918,
                                long : 43.006271,
                            } ],
                    getRestaurants : function() {
                        return factory.Restaurants;
                    },
                };
                return factory;

            });

  // 2ND / CALCULATE DISTANCE BETWEEN TWO GEOCOORDIANTES
  var GreatCircle = {

   validateRadius : function(unit) {
    var r = {
        'KM' : 6371.009,
        'MI' : 3958.761,
        'NM' : 3440.070,
        'YD' : 6967420,
        'FT' : 20902260
    };
    if (unit in r)
        return r[unit];
    else
        return unit;
    },

    distance : function(lat1, lon1, lat2, lon2, unit) {
    console.log(arguments)
    if (unit === undefined)
        unit = 'KM';
    var r = this.validateRadius(unit);
    lat1 *= Math.PI / 180;
    lon1 *= Math.PI / 180;
    lat2 *= Math.PI / 180;
    lon2 *= Math.PI / 180;
    var lonDelta = lon2 - lon1;
    var a = Math.pow(Math.cos(lat2) * Math.sin(lonDelta), 2)
            + Math.pow(Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
                    * Math.cos(lat2) * Math.cos(lonDelta), 2);
    var b = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1)
            * Math.cos(lat2) * Math.cos(lonDelta);
    var angle = Math.atan2(Math.sqrt(a), b);

    return angle * r;
    },

bearing : function(lat1, lon1, lat2, lon2) {
    lat1 *= Math.PI / 180;
    lon1 *= Math.PI / 180;
    lat2 *= Math.PI / 180;
    lon2 *= Math.PI / 180;

    console.log(lat1);
    console.log(lon1);
    console.log(lat2);
    console.log(lon2);

    var lonDelta = lon2 - lon1;
    var y = Math.sin(lonDelta) * Math.cos(lat2);
    var x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
            * Math.cos(lat2) * Math.cos(lonDelta);
    var brng = Math.atan2(y, x);
    brng = brng * (180 / Math.PI);

    if (brng < 0) {
        brng += 360;
    }

    return brng;
    },

    destination : function(lat1, lon1, brng, dt, unit) {
    if (unit === undefined)
        unit = 'KM';
    var r = this.validateRadius(unit);
    lat1 *= Math.PI / 180;
    lon1 *= Math.PI / 180;
    var lat3 = Math.asin(Math.sin(lat1) * Math.cos(dt / r) + Math.cos(lat1)
            * Math.sin(dt / r) * Math.cos(brng * Math.PI / 180));
    var lon3 = lon1
            + Math.atan2(Math.sin(brng * Math.PI / 180) * Math.sin(dt / r)
                    * Math.cos(lat1), Math.cos(dt / r) - Math.sin(lat1)
                    * Math.sin(lat3));

    return {
        'LAT' : lat3 * 180 / Math.PI,
        'LON' : lon3 * 180 / Math.PI
    };
   }

 };

 angular.module('greatCircles', []).value('GreatCircle', GreatCircle)

   /*
    * window.onload = function(){ document.getElementById("dist").innerHTML 
    =
    * Math.round(( GreatCircle.distance(48.853139,2.368999, 48.826136, 
    2.321793) *
     * 10 ) // fake data. Shall be replaced with user location + restaurant 
     location
     * 10 ); }
     */

这是我在浏览器上调用“http://localhost:3030/sez/api/user/”时的服务器响应

  [
                            {
                                Name : '11111111111',
                                venueType : 'Electrician ',
                                subCuisine : 'Fan',
                                subsubCuisine : 'Greesing, Bnding',
                                address : 'abc',
                                city : 'test',
                                country : 'xxx',
                                countryCode : 'kk',
                                lat : 36.805273,
                                long : 73.355463,
                            },
                            {
                                Name : '222222222',
                                venueType : 'Electrician ',
                                subCuisine : 'Fan',
                                subsubCuisine : 'Greesing, Bnding',
                                address : 'hii',
                                city : 'xyz',
                                country : 'abc',
                                countryCode : 'oo',
                                lat : 85.320918,
                                long : 43.006271,
                            } ]

这是视图 -

  <div  ng-repeat="restaurant in restaurantList | orderBy: 'distance' | 
  limitTo:totalDisplayed" href="#">
        <article class="item_frame">
      <div class="marker_left_container">
        <span class="venu_type_text">{{restaurant.venueType}}</span>
        <span class="distance_from_user_rest"> distance: 
  {{distanceTo(restaurant)}}</span>
        <span class="distance_from_user_rest2">from current location</span>
      </div>
      <div class="restaurant_details_container">
        <h1 class="restaurant_name_inlist">{{restaurant.Name}}</h1>
        <span class="restaurant_detail_inlist2">{{restaurant.subCuisine}}  
   <br />

    {{restaurant.subsubCuisine}}</span>
        <span class="restaurant_address">{{restaurant.address}}, <br />
        </span>
        <span class="restaurant_address">{{restaurant.cp}}, 
   {{restaurant.city}}  <br />

        </span>
        <span class="restaurant_others">{{restaurant.phoneNumber}} <br />
        </span>
        <span class="restaurant_others">{{restaurant.website}}  <br />
        </span>
             </div>

      </article><!--main article frame 1 -->

    </div>
    <button class="button button-outline button-stable custom_button_lau" ng-click="loadMore()">Load more</button>
  </div>
    </div>

您应该使用此方法从您工厂的服务器获取数据

    angular
        .module('wmapp.factory_restaurants', [ 'greatCircles' ])    
        .factory(
             'restaurantsFactory',
              function($http) {
                  return {
                     getRestaurants: function (url) {
                     return $http.get(url);
                   }
           };
        });

在控制器文件中:

$scope.restaurantList = {};
restaurantsFactory.getRestaurants(url)
                .success(function (response) {
                    $scope.restaurantList = response;
                    console.log($scope.restaurantList);
                }, function (error) {
                    console.log("Error in getting data: " + error);
                });

现在在控制器中,您可以对接收到的对象进行替换或执行任何其他计算。