I am trying to give timeout to clear my FlashService message. But it works as delay time.
FlashService.Success(("Removed Successfully"), false);
In this I am using false as condition. It means when page or location changed flash message gets cleared.
My flash.service.js
function clearFlashMessage() {
var flash = $rootScope.flash;
if (flash) {
if (!flash.keepAfterLocationChange) {
delete $rootScope.flash;
} else {
// only keep for a single location change
flash.keepAfterLocationChange = false;
}
}
}
}
function Success(message, keepAfterLocationChange) {
$rootScope.flash = {
message: message,
type: 'success',
keepAfterLocationChange: keepAfterLocationChange
};
}
function Error(message, keepAfterLocationChange) {
$rootScope.flash = {
message: message,
type: 'error',
keepAfterLocationChange: keepAfterLocationChange
};
}
In my above js I am clearing the flash message with flag as "false" when page or location changed.
I need to set the timeout in that false condition. That is if flag is false then flash message need to be cleared within some time period.
You need to call the function to clear the message after 2 sec - instead of doing $timeout(fn, interval).
i.e.
FlashService.Success(("Removed Successfully"), false);
$timeout(function(){
//clear message
//FlashService.ClearMessage(); - or whatever how you clear the message
}, 2000);
You need delete $rootScope.flash after delay. The simpliest way is to start another function called in functions Error and Success. Don't forget to inject $timeout :)
(function () {
'use strict';
angular
.module('app')
.factory('FlashService', FlashService);
FlashService.$inject = ['$rootScope', '$timeout'];
function FlashService($rootScope, $timeout) {
var service = {};
service.Success = Success;
service.Error = Error;
initService();
return service;
function initService() {
$rootScope.$on('$locationChangeStart', function () {
clearFlashMessage();
});
function clearFlashMessage() {
var flash = $rootScope.flash;
if (flash) {
if (!flash.keepAfterLocationChange) {
delete $rootScope.flash;
} else {
// only keep for a single location change
flash.keepAfterLocationChange = false;
}
}
}
}
function clearFlashMessageT() {
console.log("clear after 2 sec started")
$timeout(function(){
delete $rootScope.flash;
}, 2000);
}
function Success(message, keepAfterLocationChange) {
$rootScope.flash = {
message: message,
type: 'success',
keepAfterLocationChange: keepAfterLocationChange
};
clearFlashMessageT()
}
function Error(message, keepAfterLocationChange) {
$rootScope.flash = {
message: message,
type: 'error',
keepAfterLocationChange: keepAfterLocationChange
};
clearFlashMessageT()
}
}
})();
Related
On success message I want to navigate from uploaded page to customer page and highlight my alert as success , but my alert is not getting open. Need solution
Upload.js
if (status == 200){
$state.go('customer', {"id": $scope.customer});
$rootScope.$emit('custSucess');
}
customer.js
$rootScope.$on('custSucess',function(event){
$scope.message = {
content: [{
title: '',
msg:'hi'
}],
type: 'success'
};
});
So what I ended up doing is creating a service for handling my alerts. Here is the service code:
app.factory('AlertService', function () {
var success = {},
error = {},
alert = false;
return {
getSuccess: function () {
return success;
},
setSuccess: function (value) {
success = value;
alert = true;
},
getError: function () {
return error;
},
setError: function (value) {
error = value;
alert = true;
},
reset: function () {
success = {};
error = {};
alert = false;
},
hasAlert: function () {
return alert;
}
}
});
//And I simply set it when I need to like so:
AlertService.setSuccess({ show: true, msg: name + ' has been updated successfully.' });
//And check for it on the page that would display it like this:
if (AlertService.hasAlert()) {
$scope.success = AlertService.getSuccess();
AlertService.reset();
}`enter code here`
I have an angular js function which should be called for every 2 seconds only when the current tab is open in the browser. Is there any way to check whether the current page is active in the browser.
$scope.callAtInterval = function() {
var url = "http://127.0.0.1/test";
$http.get(url).success( function(response) {
$scope.initial = response;
},
function errorCallback(response) {
$scope.result=response;
});
}
$interval( function(){ $scope.callAtInterval(); }, 5000);
}
I think below piece of code is self-explanatory
import { HostListener} from "#angular/core";
#HostListener("window:visibilitychange", ["$event"])
onVisibilityChange($event) {
const isVisible = $event.target.visibilityState === 'visible';
this.logger.info(isVisible);
if (isVisible) {
// tab is visible
} else {
// tab is not-visible
}
}
You would use the focus and blur events of the window:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// cancel your interval function
break;
case "focus":
// emit your interval function
break;
}
}
$(this).data("prevType", e.type);
})
I have code like this
(function (app) {
app.controller('productListController', productListController)
productListController.$inject = ['$scope', 'apiService', 'notificationService', '$ngBootbox', '$filter'];
function productListController($scope, apiService, notificationService, $ngBootbox, $filter) {
$scope.products = [];
$scope.page = 0;
$scope.pagesCount = 0;
$scope.getProducts = getProducts;
$scope.keyword = '';
$scope.search = search;
$scope.deleteProduct = deleteProduct;
$scope.selectAll = selectAll;
$scope.deleteMultiple = deleteMultiple;
function deleteMultiple() {
var listId = [];
$.each($scope.selected, function (i, item) {
listId.push(item.ID);
});
var config = {
params: {
checkedProducts: JSON.stringify(listId)
}
}
apiService.del('/api/product/deletemulti', config, function (result) {
notificationService.displaySuccess('Deleted successfully ' + result.data + 'record(s).');
search();
}, function (error) {
notificationService.displayError('Can not delete product.');
});
}
$scope.isAll = false;
function selectAll() {
if ($scope.isAll === false) {
angular.forEach($scope.products, function (item) {
item.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.products, function (item) {
item.checked = false;
});
$scope.isAll = false;
}
}
$scope.$watch("products", function (n, o) {
var checked = $filter("filter")(n, { checked: true });
if (checked.length) {
$scope.selected = checked;
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
}, true);
function deleteProduct(id) {
$ngBootbox.confirm('Are you sure to detele?').then(function () {
var config = {
params: {
id: id
}
}
apiService.del('/api/product/delete', config, function () {
notificationService.displaySuccess('The product hase been deleted successfully!');
search();
}, function () {
notificationService.displayError('Can not delete product');
})
});
}
function search() {
getProducts();
}
function getProducts(page) {
page = page || 0;
var config = {
params: {
keyword: $scope.keyword,
page: page,
pageSize: 20
}
}
apiService.get('/api/product/getall', config, function (result) {
if (result.data.TotalCount == 0) {
notificationService.displayWarning('Can not find any record.');
}
$scope.products = result.data.Items;
$scope.page = result.data.Page;
$scope.pagesCount = result.data.TotalPages;
$scope.totalCount = result.data.TotalCount;
}, function () {
console.log('Load product failed.');
});
}
$scope.getProducts();
}
})(angular.module('THTCMS.products'));
So my problem is when i loading data the application take me some time to load data.
I need load data as soon as
Is the any solution for this?
Since you are loading data via api call, there will be a delay. To handle this delay, you should display a loading screen. Once the data is loaded, the loading screen gets hidden and your main screen is visible. You can achieve this using $http interceptors.
See : Showing Spinner GIF during $http request in angular
The api-call is almost certainly causing the delay. Data may be received slowly via the api-call so you could display any sort of loading text/image to notify the use that the data is being loaded.
If u want the data ready at the time when controller inits, u can add a resolve param and pass the api call as a $promise in the route configuration for this route.
I have a notifications dropdown in my AngularJS application. I want to call a function within the function that open the dropdown. Here is what I mean:
$scope.showNotif = false;
$scope.toggleNotifDropdown = function(event) {
$scope.showNotif = !$scope.showNotif;
readNotifications = function() {
NotificationService.readNotifs().then(
function(success) {
console.log("Notifications read!");
},
function(errors) {
console.log("Something wrong happened.");
}
);
};
if($scope.showNotif) {
$document.bind('click', $scope.globalNotifClose);
} else {
$document.unbind('click', $scope.globalNotifClose);
}
event.stopPropagation();
};
The notifications dropdown works perfectly, I just can't get that function readNotifications() to work for me. Any suggestions would be great! Thanks!
There is no point in declaring the function within your scope function and you never call it either. Declare it outside and call it from inside
$scope.toggleNotifDropdown = function (event) {
$scope.showNotif = !$scope.showNotif;
// call the function declared below
readNotifications();
if ($scope.showNotif) {
$document.bind('click', $scope.globalNotifClose);
} else {
$document.unbind('click', $scope.globalNotifClose);
}
event.stopPropagation();
};
// function declaration
var readNotifications = function () {
NotificationService.readNotifs().then(
function (success) {
console.log("Notifications read!");
},
function (errors) {
console.log("Something wrong happened.");
});
};
myApp.services.factory('GCMHelper', ($q)->
pushNotification = {}
_init = ()->
defer = $q.defer()
ionic.Platform.ready(()->
pushNotification = window.plugins.pushNotification;
window.onNotification = (res)->
console.log('onNotification', res)
defer.resolve()
)
return defer.promise
return {
register: ()->
_init().then(()->
pushNotification.register(
(res)->
console.log('gcm register success', res)
(err)->
console.log('gcm register err', err)
{
"senderID": "*********",
"ecb": "onNotification"
}
);
)
}
)
in controller:
GCMHelper.register()
(Please excuse my poor English)
I'm tring Cordova PushPlugin with Cordova 4.2 and Ionic beta 14, it got success callback every time with "OK" string, but ecb onNotification never fired, and no error at console. I almost have no ideal with that..., any one help?
Use the following for Push Notification in Android and iOS. It will work properly for you. After install the app, user will need to open the app for call ecb methods. In iOS, PushNotifcation's register success method will returns the mobile register id in result but in android, it will return only OK. In Android, onNotificationGCM method will be called for two type event 1) RegisterId and 2) Notification Message. I have also added the showNotificationAPN/GCM method for show notification popups with $ionicPopup.alert().
.run(function ($ionicPlatform, PushProcessingService) {
$ionicPlatform.ready(function () {
try {
PushProcessingService.initialize();
} catch (e) {
//hide event
}
})
})
.factory('PushProcessingService', ["$window", "$ionicPopup", function ($window, $ionicPopup) {
function onDeviceReady() {
var pushNotification = window.plugins.pushNotification;
if (ionic.Platform.isAndroid()) {
pushNotification.register(gcmSuccessHandler, gcmErrorHandler, {'senderID': 'XXXXXXXXXXXXXX', 'ecb': 'onNotificationGCM'});
} else if (ionic.Platform.isIOS()) {
var config = {
"badge": "true",
"sound": "true",
"alert": "true",
"ecb": "pushCallbacks.onNotificationAPN"
};
pushNotification.register(gcmSuccessHandler, gcmErrorHandler, config);
}
var addCallback = function addCallback(key, callback){
if(window.pushCallbacks == undefined){
window.pushCallbacks = {};
}
window.pushCallbacks[key] = callback({registered:true});
}
}
function gcmSuccessHandler(result) {
console.log("Register push notification successfully : " + result);
if (ionic.Platform.isIOS()) {
var mobileType = "ios";
var mobileRegisterId = result;
// Save the ios mobile register Id in your server database
// call the following method on callback of save
addCallback("onNotificationAPN", onNotificationAPN);
}
}
function gcmErrorHandler(error) {
console.log("Error while register push notification : " + error);
}
return {
initialize: function () {
document.addEventListener('deviceready', onDeviceReady, false);
},
registerID: function (id) {
var mobileType = "android";
// Save the android mobile register Id in your server database
console.log("RegisterId saved successfully.");
},
showNotificationGCM: function (event) {
$ionicPopup.alert({
title: "Pajhwok Notification",
subTitle: event.payload.type,
template: event.payload.message
});
},
showNotificationAPN: function (event) {
$ionicPopup.alert({
title: event.messageFrom + "..",
subTitle: event.alert,
template: event.body
});
}
}
}])
onNotificationAPN = function(event) {
if (!event.registered) {
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var myService = injector.get('PushProcessingService');
myService.showNotificationAPN(event);
} else {
console.log("Registered successfully notification..");
}
}
function onNotificationGCM(e) {
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var myService = injector.get('PushProcessingService');
myService.registerID(e.regid);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var myService = injector.get('PushProcessingService');
myService.showNotificationGCM(e);
break;
case 'error':
alert('<li>ERROR :' + e.msg + '</li>');
break;
default:
alert('<li>Unknown, an event was received and we do not know what it is.</li>');
break;
}
}