0
所以,我在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 • 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
};
};
}]);
所以我有一個已定義properties
對象,並希望當我訪問一個頁面來覆蓋它。問題是,當我回到家時,它不會設置默認值。很明顯,它在頁面加載後實例化,然後保持不變,直到更改。 這樣做的最佳方法是什麼?
我曾嘗試向路由添加一個偵聽器,就像@Raul A.建議的那樣,但它不工作。從控制檯輸出:
我想你建議和我編輯我的問題與結果。看起來像是我直接打開'/ page',它從'MainController'而不是'PagesController'獲取值。 –