Javascript 在Angular中的外部库回调

Javascript 在Angular中的外部库回调,javascript,jquery,angularjs,Javascript,Jquery,Angularjs,我正在尝试从常规js转换到angular,当我使用GooglePlaces库时,我得到了奇怪的结果(我假设它与任何其他异步回调都是一样的) 代码如下: var sparkApp = angular.module('sparkApp',[]); sparkApp.controller('GooglePlacesListCtrl', function GooglePlacesListCtrl($scope) { $scope.places = [ {'name': 'Nex

我正在尝试从常规js转换到angular,当我使用GooglePlaces库时,我得到了奇怪的结果(我假设它与任何其他异步回调都是一样的)

代码如下:

var sparkApp = angular.module('sparkApp',[]);

sparkApp.controller('GooglePlacesListCtrl', function GooglePlacesListCtrl($scope) {
    $scope.places = [
        {'name': 'Nexus S',
            'formatted_address': 'Fast just got faster with Nexus S.'},
        {'name': 'Motorola XOOM™ with Wi-Fi',
            'formatted_address': 'The Next, Next Generation tablet.'},
        {'name': 'MOTOROLA XOOM™',
            'formatted_address': 'The Next, Next Generation tablet.'}
    ];

    // ***
    // **** THIS IS TIED TO AN NG-CLICK
    // ***
    $scope.gmapSearchButtonClicked = function ()
    {
        var query = $("#location_search").val();
        console.log(getMapRadius());
        var request = {
            location: map.getCenter(),
            radius: getMapRadius(),
            query: query
        };

        service.textSearch(request, $scope.searchCallback);
    }

    $scope.searchCallback = function (results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            // ***
            // **** THIS IS NOT WORKING - IS IT BECAUSE $SCOPE IS IN AN ASYNC CALLBACK?
            // **** IT ALSO SHOWS UP IN CONSOLE CORRECTLY
            // ***
            $scope.places = [{'name': 'Test Scenario',
                    'formatted_address': 'New Stuff'}];
            console.log($scope.places);
        }
    }
});

基本上,问题是我的位置没有在模板中更新。它们在开始时加载良好(使用所有nexus内容),但在我单击search(调用gmapSearchButtonClicked)并触发回调后,没有任何内容得到更新,即使控制台中的所有内容都正确显示。对我来说更奇怪的是,如果我再次单击“搜索”,模板就会用新数据更新。有什么想法吗?

想出来了。基本上,问题在于没有应用对places数组的更改,因为回调来自另一个库。解决方案将其包装为$apply,如下所示:

        $scope.$apply(function () {
            $scope.places = [{'name': 'New',
                'formatted_address': 'New Stuff'}];
            console.log($scope.places);
        });
这里有一个很好的完整解释: