我想顯示的index.html頁上的警報消息(成功,警告,危險):
...
</header>
<div ng-controller="AlertController">
<alert ng-repeat="alert in alerts" type="alert.status" close="closeAlert($index)">{{ alert.message }}</alert>
</div>
<div ng-view></div>
...
要做到這一點,我寫了一個AlertController在控制器.js文件。通過$ broadcast/$ on接收警報可能是一個好主意。
Controllers.controller('AlertController', ['$scope', '$rootScope',
function ($scope, $rootScope) {
$scope.alerts = [];
$rootScope.$on('alert:success', function(message) {
$scope.alerts.push({'status': 'success', 'message': message});
});
$rootScope.$on('alert:warning', function(message) {
$scope.alerts.push({'status': 'warning', 'message': message});
});
$rootScope.$on('alert:danger', function(message) {
$scope.alerts.push({'status': 'danger', 'message': message});
});
$scope.closeAlert = function (alert) {
return this.closeAlertIndex($scope.alerts.indexOf(alert));
};
$scope.closeAlertIndex = function (index) {
return $scope.alerts.splice(index, 1);
};
}]);
但是,當我使用其他控制器的警報沒有得到顯示:
Controllers.controller('LocationController', ['$scope', '$rootScope', '$routeParams', 'LocationService',
function ($scope, $rootScope, $routeParams, LocationService) {
$scope.Location = {};
$scope.Locations = [];
$scope.queryLocation = function() {
LocationService.query({active: $routeParams.active}, function (locations) {
$scope.Locations = locations;
$rootScope.$broadcast('alert:success', "Location queried: active = " + $routeParams.active);
console.log("Location queried");
}, function (error) {
$rootScope.$broadcast('alert:warning', "Unable to query location: " + error.message);
console.log("Unable to query location");
});
};
$scope.getLocation = function() {
LocationService.get({id: $routeParams.id}, function (location) {
$scope.Location = location;
$rootScope.$broadcast('alert:success', "Location got: " + location.id);
console.log("Location got");
}, function (error) {
$rootScope.$broadcast('alert:warning', "Unable to get location: " + error.message);
console.log("Unable to get location");
});
};
}]);
我能看到的console.log()消息,而不是警報。在日誌中,我也看到了alert.html上的404錯誤。我必須創建一個alert.html文件才能使用標籤嗎?
我讀過一些其他帖子,他們建議使用服務而不是控制器,但這不適用於我的頁面。此外,我認爲這是一個簡單的解決方案,只是廣播警報...
我該如何解決這個問題?
乾杯
感謝我的迴應,我重寫了代碼。我不得不做以下得到它的工作:
警示標籤沒有工作,所以我從UI的bootstrap.min.js改爲UI的自舉tpls.min.js
基於glepretre的建議
新AlertController新PubSubService:
Controllers.controller( 'AlertController',[ '$範圍', 'PubSubService', 功能($範圍,PubSubService){$ SCO pe.alerts = [];現在
$scope.addAlert = function(status, message) { $scope.alerts.push({'status': status, 'message': message}); }; $scope.closeAlert = function(index) { $scope.alerts.splice(index, 1); }; PubSubService.subscribe('alert', $scope.addAlert);}]);
我可以用
PubSubService.publish('alert', 'warning', 'Unable to get location: ' + error.message);
添加警報,但該方案沒有使用$廣播。
我使用類似情況下的pub/sub服務,如果你想嘗試它:https://github.com/glepretre/angular-pubsub – glepretre
它是否像你想與angular-pubsub一樣工作? :) – glepretre