仅在AngularJS中加载一次数据

时间:2018-03-03 09:02:12

标签: javascript angularjs

我正在使用AngularJS创建一个项目,我想在Angular控制器中加载一次数据。我的代码有效,但有时会显示空数据。

这是我的代码:

 if(!$scope.locations){
      $scope.promise = pricingService.getIPVPNLocations().then(function(response){
           $scope.locations = response.data;
        })
  }

以下是观点:

 <select ng-model="pricing.ipvpnLocation" ng-init="pricing.ipvpnLocation = location[0].uuid" ng-options="location as location.name for location in locations |  orderBy:'name' track by location.uuid ">
            <option value="">Select Location </option>

        </select>

我的服务如下:

this.getIPVPNLocations = function (epuuid,serviceuuid) {
        var deferred = $q.defer();
        var url = '/pricing/getIPVPNLocations/'+epuuid+"/"+serviceuuid;
        $http.get(url).
            then(function (response) {
                deferred.resolve({data: response.data.message, status: response.data.statusCode});
            }).
            catch(function (response) {
                deferred.reject(response);
            });
        return deferred.promise;
    };

2 个答案:

答案 0 :(得分:0)

使用服务,因为它们是单身人士。只需在服务中创建一个局部变量,它将在整个应用程序生命周期中保持不变

答案 1 :(得分:0)

您需要在服务中再添加一个包含位置数据的变量。

目标是首先检查是否存在位置数据,然后进行ajax调用。 服务将是......

.service('YourService', ['$http', '$q', function ($http, $q) {

    var  locations = [];

    return {

        getLocations: function (epuuid,serviceuuid) {
            var deferred = $q.defer();

            if(locations.length){
                 deferred.resolve(locations);
            }else{               
                var url = '/pricing/getIPVPNLocations/'+epuuid+"/"+serviceuuid;
                $http.get(url).
                    then(function (response) {
                        locations = response.data; //assuming that response.data is an array of locations
                        deferred.resolve(locations);
                    },function (reason) {
                        deferred.reject(reason);
                    }).
                    catch(function (response) {
                        deferred.reject(response);
                    });
            }

            return deferred.promise;
        }
    }
}])

在控制器

$scope.locations = [];    
YourService.getLocations(param1,param2).then(function(locations){
        $scope.locations = locations;
    },function(reason){
        console.log('Something wrong: ',reason);
    })