每次点击ngRoute url后都会调用AngularJS控制器

时间:2015-06-11 08:48:27

标签: javascript angularjs

我遇到以下代码问题。当我转到main控制器网址#/时,Angular自然会调用主控制器 - 它会执行AJAX请求。问题是,当我再次点击#/some-url,然后再点击#/ url时,会再次执行此AJAX请求,由于性能原因,这是不可取的和不必要的。我认为控制器只被调用一次,但它看起来并非如此,至少是ngRoute

angular.module('robotsApp', ['ngRoute', 'controllers'])

    .config(['$routeProvider', function($routeProvider){
        var root = '/static/js/partials/';
        $routeProvider.
            when('/', {
                templateUrl: root + 'main.html',
                controller: 'main as main'
            }).
            when('/some-url', {
                templateUrl: root + 'some_template.html',
                controller: 'someController'
            }).
            otherwise({
                redirectTo: '/'
            });
    }]);

angular.module('controllers', [])
    .controller('main', ['$http', function($http){
        $http.get('/user/recent-gain-loss').success(function(data){
            this.recent_gain_loss = data;
        }.bind(this));
    }]);

<p>{{ main.recent_gain_loss }}</p>

1 个答案:

答案 0 :(得分:2)

将数据保存到某个值,然后检查数据是否已设置。

angular.module('values', [])
.value('recentGainLoss', {})
angular.module('controllers', ['values'])
    .controller('main', ['$http', 'recentGainLoss', function($http, recentGainLoss){

        if (Object.keys(recentGainLoss).length < 1) {
          $http.get('/user/recent-gain-loss').success(function(data){
            recentGainLoss = angular.extend(recentGainLoss, data);

           });

        }
        this.recent_gain_loss = recentGainLoss;

    }]);