Javascript 每次单击ngRoute url后调用AngularJS控制器
我有以下代码的问题。当我转到Javascript 每次单击ngRoute url后调用AngularJS控制器,javascript,angularjs,Javascript,Angularjs,我有以下代码的问题。当我转到maincontrollerurl#/时,Angular自然调用主控制器-它执行AJAX请求。问题是,当我再次单击#/someURL,然后再次单击#/url时,会再次执行此AJAX请求,由于性能原因,这是不需要的。我以为控制器只被调用一次,但看起来不是这样,至少对于ngRoute angular.module('robotsApp', ['ngRoute', 'controllers']) .config(['$routeProvider', functio
main
controllerurl#/
时,Angular
自然调用主控制器-它执行AJAX
请求。问题是,当我再次单击#/someURL
,然后再次单击#/
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('robotsApp',['ngRoute','controllers'))
.config(['$routeProvider',函数($routeProvider){
var root='/static/js/partials/';
$routeProvider。
当(“/”{
templateUrl:root+'main.html',
控制器:“主作为主”
}).
当(“/some url”{
templateUrl:root+“some_template.html”,
控制器:“someController”
}).
否则({
重定向到:'/'
});
}]);
角度模块('控制器',[]))
.controller('main',['$http',函数($http){
$http.get('/user/recent-gain-loss').success(函数(数据){
最近的收益和损失=数据;
}.约束(这个);
}]);
{{main.recently_gain_loss}
将数据保存到值中,然后检查数据是否已设置
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;
}]);
角度模块('值',[])
.value('recentGainLoss',{})
角度模块('controllers',['values']))
.controller('main',['$http','recentGainLoss',函数($http,recentGainLoss){
if(对象键(最近无)。长度<1){
$http.get('/user/recent-gain-loss').success(函数(数据){
recentGainLoss=角度扩展(recentGainLoss,数据);
});
}
最近的收益和损失=最近的收益和损失;
}]);
所以我需要使用服务来解决这个问题?angular是否总是在单击相应的url时调用与ngRoute url连接的控制器?我不能肯定地告诉您,但我认为确实如此(我将在代码中查看它)。在应用程序中保存状态的任何方法都最好将其抽象为服务,因为保存任何状态不是控制器的责任。此外,您可以在不同的组件上共享它,并且可以安全地声明您拥有最新版本的dataBtw,在上面的代码中有一个文本,angular没有方法extends,而是extend:)