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

AngularJS controller called every time after ngRoute url is clicked

本文关键字:调用 AngularJS 控制器 url ngRoute      更新时间:2023-09-26

我对下面的代码有问题。当我转到控制器 url #/ 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>

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

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;
    }]);