我正在尝试在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>
...
为此,我在controllers.js中编写了一个AlertController。通过$ 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-bootstrap-tpls.min.js
基于glepretre提案的新PubSubService
New AlertController:
Controllers.controller('AlertController',['$ scope','PubSubService', function($ scope,PubSubService){ $ scope.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);
但是这个解决方案不是使用$ broadcast。
答案 0 :(得分:4)
$ broadcasts只去DOWN范围,$ emits去UP范围。使用$ emit结合$ rootScope。由于$ rootScope是顶级范围,因此所有$ emits都会触及它。另外,我把它放在服务而不是控制器中,但我真的不知道你在做什么。