我在运行块中解析有关应用程序加载的数据...
.run(function($rootScope, $q, teams, schools, news, games){
// go out and grab all the relevant data
$rootScope.showSplash = true;
$q.all([
$rootScope.school = schools.get({id:1}),
$rootScope.teams = teams.query({id:1}),
$rootScope.news = news.query({id:1}),
$rootScope.games = games.query({id:1})
]).then(function(){
setTimeout(function(){
$rootScope.showSplash = false;
$rootScope.$digest();
}, 1000);
})
})
我有一个控制器,其范围应该通过$ rootScope克隆数据......
.controller('NewsDetailCtrl', function ($scope, $routeParams) {
$scope.newss = $scope.news.filter(function(news){
return news.id == $routeParams.id;
}).shift();
});
如果用户在new-detail.html页面上,则不存在任何数据,因为$ scope克隆了一个空数组。收到该信息后是否可以重新运行控制器?
答案 0 :(得分:2)
为了获得更好的解决方案,您可以创建一个装饰缓存。
看一下angularJS中的装饰提供者: https://docs.angularjs.org/api/auto/service/ $提供
这将允许您将业务逻辑包装在服务中。然后使用缓存层装饰该服务,以确保仅检索一次。如果需要,我可以发布一个例子。
**更新添加示例**
var upstream = angular.module('thirdParty', []);
upstream.service('emailService', function() {
this.email = "";
this.setContent = function(content) {
this.email = content;
};
this.send = function(recipient) {
return 'sending "' + this.email + '" to ' + recipient;
};
});
var app = angular.module('myApp', ['thirdParty']);
app.config(function($provide) {
$provide.decorator('emailService', function($delegate) {
// myApp depends on the emailService from a third-party module, but the service is lacking a way to send email with signature.
// To avoid reinventing the wheel and, as well as, maintaining a good habit of leaving third-party module intact,
// I use $provide.decorator here to enhance emailService.
$delegate.sendWithSignature = function(recipient, signature) {
return 'sending "' + this.email + '" to ' + recipient + " by " + signature;
};
return $delegate;
});
});
app.controller('MainCtrl', function($scope, emailService) {
emailService.setContent("Greeting!!");
$scope.emailComplete = emailService.sendWithSignature('a@a.com', 'tamakisquare');
});
我添加了装饰器的示例用法。希望这有帮助