gpt4 book ai didi

javascript - 在每个页面更改/请求时实例化的 Angular 服务

转载 作者:行者123 更新时间:2023-12-03 07:01:22 25 4
gpt4 key购买 nike

所以,我正在 AngularJS (1.5) 迈出第一步。我正在尝试构建一个功能,让我可以根据路线更改布局中的一些内容。

据我了解,我需要为此提供服务。基本上我的设置是:

'use strict';

/* App Module */

var app = angular.module('app', [
'ngRoute',
'appControllers',
'AppServices'
]);

app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
template: '<h1>Home page</h1>',
controller: 'MainController'
}).when('/page', {
template: '<h1>Page</h1>',
controller: 'PagesController'
}).otherwise({
redirectTo: '/'
});
}]);
var appControllers = angular.module('appControllers', []);

appControllers.controller('MainController', ['$rootScope', 'AppSetup', function($scope, AppSetup) {
$scope.app = AppSetup.build();
console.log('home');
}]);

appControllers.controller('PagesController', ['$rootScope', 'AppSetup', function($scope, AppSetup) {
AppSetup.setProperties({
meta: {
title: 'My Second Page'
}
});
console.log('page');
$scope.app = AppSetup.build();
}]);

var AppServices = angular.module('AppServices', []);

AppServices.service('AppSetup', [function() {
var properties = {
meta: {
title: 'My App &bull; Best of the best'
}
},
styles;
this.setProperties = function(input) {
this.properties = angular.extend(properties, input);
};
//TODO: This will override app-wide styles.
this.setStyles = function(input) {
this.styles = angular.extend({}, input);

};
this.build = function() {
return {
properties: properties,
styles: styles
};
};
}]);

Plunkr here

因此,我有一个已定义的 properties 对象,并且希望在访问页面时覆盖它。问题是当我回到家时,它没有设置默认值。显然,它是在页面加载后实例化的,然后保持不变直到发生更改。执行此操作的最佳方法是什么?

我已经尝试按照 @Raul A. 的建议向路线添加监听器,但它不起作用。控制台输出:

enter image description here

Plunkr here

最佳答案

如果您正在使用路由,则可以使用 $routeChangeSuccess 事件并在监视它的函数中进行更改:

$rootScope.$on("$routeChangeSuccess", function(currentRoute, previousRoute){
//Do you changes here
});

关于javascript - 在每个页面更改/请求时实例化的 Angular 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37052475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com