简体   繁体   中英

Javascript function & setting $scope variable

I have a function that gets called from my controller to my service.

GridService.getHeaders($scope.grid);

Service is below...

    function getHeaders(grid){
    var deferred = $q.defer();
    $http.put('v1/headers', grid).success(function (data) {
        deferred.resolve(data);
    }).error(function (data, status, headers, config) {
        deferred.reject(data);
    });
    return deferred.promise;
}

I need to get the data I receive from this and set it to a $scope variable in my controller...

$scope.headers = (Data from getHeader function)

Which will then get injected into this function. Sorry if this all seems confusing... The way I had it originally was just setting

$scope.headers = GridService.getHeaders($scope.grid);

However $scope.headers always returns empty.

    function getFullHeaders(headers, highlightFilteredHeader){
        var returnArray = [];

        for(var i = 0; i < headers.length; i++ ){
            returnArray.push({
                field: headers[i].key, 
                displayName: headers[i].name,
                enablePaginationControls: true, 
                headerCellClass: highlightFilteredHeader,  
                enableFiltering: true,  
                enableSorting: true, 
                visible: true,  
                filter: { term: "", }
            });
        }

        return returnArray;
}

Your getHeaders method returns a promise. Therefore, if you want to react to the promise being resolved, you have to use .then(fn) .

Try:

GridService.getHeaders($scope.grid).then(function(response) {
    $scope.headers = response;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM