简体   繁体   中英

Scope not updated outside resource callback function

I have a factory in AngularJS called WebService which returns a $resource object.

angular.module('cstarsServices')
.factory('WebService', function ($resource)
{
    return $resource("some_url_here/:op1/:op2/:op3/:op4",
            {op1: 'indexes'},
            {
                getIndexes: {
                    isArray: true,
                    method: 'GET'
                }

            }
        );
});

In one of my controllers, I call getIndexes:

WebService.getIndexes(function(data){

    // SearchIndex Table
    $scope.languages = [];
    var languages = [];
    var ajaxResponse = [];


    angular.forEach(data, function (item, i)
    {
        if (item.sourceTypes != null)
        {
            ajaxResponse.push({ selected: false, name: item.name, languages: item.sourceTypes[0] });
            languages[item.sourceTypes[0]] = item.sourceTypes[0];
        }
    });
    $scope.searchIndexes = ajaxResponse;


    for (var key in languages)
    {
        $scope.languages.push(languages[key]);
    }
    $scope.language = languages[0];
});
//This is undefined
alert($scope.searchIndexes);

However this doesn't seem to update the $scope correctly: for example the value of $scope.searchIndexes is defined and has the correct data inside of the function but is undefined outside . What's going on, and how can I get the $scope to update for the entire controller and not just inside the callback function? Thanks in advance for any help.

Your WebService.getIndexes function is making an asynchronous AJAX call. The alert() command right below it is executed right after the WebService.getIndexes call is made, but before any data is actually returned from the back-end service. Thus the $scope assignments you do within the AJAX call actually happens after the alert() command (or any other code in your controller that is not in a function).

Try putting an alert($scope.searchIndexes); at the end of your AJAX call. You'll notice that the output from this alert will actually appear below the output from your alert() outside of your AJAX call.

It's hard to recommend a work-around without seeing the rest of your controller. But a general rule of thumb here would be to only reference $scope.searchIndexes within functions. As long as those functions are then only called after the controller fully loads, you'll be able to reference $scope.searchIndexes without issue.

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