AngularJS $location.path(path) not updating at first

狂风中的少年 提交于 2019-12-06 16:06:15

Okay, at last I got this to work. As I suspected, it's a matter of getting $scope.$apply() in the right place.

Google Analytics calls have a callback inside a callback and the inner callback has parameters. So in the end I do this inside my AngularJS service:

// this function will be an Angular service (see last line)

var Graphdata = function($rootScope) {
    var gAPIResult;
    // called by apiQuery
    var handle_results = function(results) {
        gAPIResult = results;
        $rootScope.$apply(function() {
            /* ...
            use "gAPIResult" instead of "results" and call
            $rootScope.$broadcast('GraphUpdate', 1);
            on success
            ... */
        });
    };
    var compare_mobile_cpus = function() {
        var queryParams, apiQuery;
        queryParams = { /* could be anything */
            'ids': 'ga:78752930',
            'start-date': '2013-11-07',
            'end-date': '2013-11-09',
            'metrics': 'ga:visits',
            'dimensions': 'ga:EventLabel,ga:date' ,
            'filters': 'ga:eventAction==cputype'
        };
        try {
            apiQuery = gapi.client.analytics.data.ga.get(queryParams);
            apiQuery.execute(handle_results);
        } catch (e) {
            return false;
        }
        return true;
    };
   return {
        init_n_load: function() { // called from the controller
            gapi.client.setApiKey('AIzaSyCGcXFQzom1vE5-s');  // API KEY
            gapi.client.load('analytics', 'v3', compare_mobile_cpus);
        },
    };
};

angular.module('analytics2App').service('Graphdata', Graphdata);

that is, init_n_load() has callback compare_mobile_cpus() which has callback handle_results() which contains $rootScope.$apply()... and because that last callback has a results parameter, I have to stash it on the service before launching $apply()

This does work... but is it an optimal pattern? Saving "results" feels a little dirty.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!