AngularJS:使用$broadcast显示警报



我正试图在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-botstrap.min.js更改为ui-botStrap-tpls.min.js

  • 基于gleprette提议的新PubSubService

  • 新型警报控制器:

    Controllers.controller("AlertController",["$scope","PubSubService",函数($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。

$只广播向下作用域,$发射向上作用域。将$emit与$rootScope结合使用。由于$rootScope是顶级作用域,所有$emits都会命中它。此外,我会把它放在服务中,而不是控制器中,但我真的不知道你在做什么。

最新更新