此外也可利用$rootScope.$broadcast事件的方法來統一處理全域的訊息
Directive
<alert ng-repeat="alert in alerts"
type="alert.type"
close="alert.close($index)">{{alert.msg}}</alert>
AlertService Factory
支援timeout自動關閉訊息
app.factory('AlertService', ['$rootScope', '$timeout', '$log',
function($rootScope, $timeout, $log) {
var alertService = this;
$rootScope.alerts = [];
return alertService = {
add: function(type, msg, timeout) {
$rootScope.alerts.push({
type: type,
msg: msg,
close: function() {
return alertService.closeAlert(this);
}
});
if(typeof(timeout) == 'undefined'){
timeout = 5000;
}
if (timeout) {
$timeout(function() {
alertService.closeAlert(this);
}, timeout);
}
},
closeAlert: function(alert) {
$log.log(alert);
return this.closeAlertIdx($rootScope.alerts.indexOf(alert));
},
closeAlertIdx: function(index) {
return $rootScope.alerts.splice(index, 1);
},
clear: function(){
$rootScope.alerts = [];
}
};
}
])
Controller
angular.module('myApp.controllers').controller('LoginCtrl', ['$rootScope','$scope', '$log', 'AuthService', 'AlertService','$location',
function($rootScope, $scope, $log, AuthService, AlertService, $location) {
$log.log('load login page');
$scope.login = function(credentials) {
$log.log('press login button');
$log.log(credentials);
AuthService.login(
credentials, function(data, status, headers, config) {
$log.log('success to call login');
$log.log(data);
if (data.status == 200) {
$log.log('go to default users page');
//go to home
$location.path('/users');
}else if (data.status == 500){
AlertService.add('danger','不正確的帳號或密碼');
}
}, function(data, status, headers, config) {
$log.log('fail to call login');
AlertService.add('danger','伺服器發生錯誤,請重新再試');
});
};
}
]);
https://coderwall.com/p/r_bvhg
沒有留言:
張貼留言
留個話吧:)