Cancel function that has $timeout running - angularjs

I have the following code. It checks a factory that polls a server every few minutes. It works fine, but I want to pause the "fetchDataContinously" method when a modal is opened, and resume it when the modal is closed. In short, I need to find a way to toggle the "fetchDataContinously" on the opening and closing of modals. Please advise, or let me know if my question is not clear.
angular.module('NavBar', []).controller('NavBarCtrl', function NavBarCtrl($scope,$modal,$timeout,MyPollingService) {
var ctrl = this;
fetchDataContinously ();
function fetchDataContinously () {
MyPollingService.poll().then(function(data) {
if(data.response[0].messages[0].important_popup){
ctrl.showImportantNotice(data.response[0].messages[0]);
return;
}
$timeout(fetchDataContinously, 3000);
});
}
ctrl.showNotices = function () {
var noticesModalOptions = {
templateUrl: "notices.html",
controller: "NoticesCtrl",
controllerAs: "ctrl",
show: true,
scope: $scope,
resolve: {
notices: function(NoticesFactory) {
return NoticesFactory.getMessages();
}
}
}
var myNoticesModal = $modal(noticesModalOptions);
myNoticesModal.$promise.then(myNoticesModal.show);
}
ctrl.showImportantNotice = function (importantNotice) {
ctrl.importantNotice = importantNotice;
var importantNoticeModalOptions = {
templateUrl: "/importantNotice.html",
controller: "ImportantNoticeCtrl",
controllerAs: "ctrl",
show: true,
scope: $scope,
onHide: function() {
console.log("Close !");
fetchDataContinously();
},
onShow: function() {
console.log("Open !");
}
}
var myImportantNoticeModal = $modal(importantNoticeModalOptions);
myImportantNoticeModal.$promise.then(myImportantNoticeModal.show);
}
})

Wrap your $timeout in function and return it's promise
var timer;
function startPolling(){
return $timeout(pollData, 3000);
}
// start it up
timer = startPolling();
To cancel:
$timeout.cancel(timer);
Then to start again :
timer = startPolling();

Related

How to choose the trigger order

I have this directive:
module.directive("myDirective", function() {
return {
restrict: 'E',
templateUrl: 'pathToUrl',
controller: myCtrl,
controllerAs: vm,
bindToController: true,
scope: {
flag: '=',
toggleFlagFunc: '='
}
}
function myCtrl() {
let vm = this;
vm.olMap = new ol.Map({/*map init here*/})
vm.olMap.on("click", clickFunc);
function clickFunc() {
if (vm.flag) {
// Do some logic
vm.toggleFlagFunc();
}
}
}
}
This is the template url:
<div class="first-div"></div>
<div class="second-div"></div>
<div class="map-container-div"></div>
<div class="third-div"></div>
And this instance:
<my-directive flag="vm.flag" toogle-flag-func="vm.toogleFlagFunc" ng-click="vm.myDirectiveClicked()"></my-directive>
And this is the parent ctrl:
function parentCtrl {
let vm = this;
vm.flag = false; // The flag changed to true somewhere
vm.toggleFlagFunc = () => {
vm.flag = !vm.flag;
// Some Other Logic
}
vm.myDirectiveClicked = () => {
if (!vm.flag) {
// Do some logic here
}
}
}
My problem is when vm.flag evaluates to true and I click on the map-container-div, the order of the called functions is vm.toogleFlagFunc and then vm.myDirectiveClicked.
Can I change the order some how?
Thanks in advance!

AngularJS - moving Material mdDialog to service

I'm trying to cleanup code of one of my controllers which became too big. First I have decided to move attendee registration, which uses AngularJS Material mdDialog, to the service.
Original (and working) controller code looks like:
myApp.controller('RegistrationController', ['$scope','$routeParams','$rootScope','$location','$filter','$mdDialog', function($scope, $routeParams, $rootScope, $location, $filter, $mdDialog){
var attendee = this;
attendees = [];
...
$scope.addAttendee = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'views/regForm.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
controllerAs: 'attendee',
fullscreen: $scope.customFullscreen, // Only for -xs, -sm breakpoints.
locals: {parent: $scope}
})
.then(function(response){
attendees.push(response);
console.log(attendees);
console.log(attendees.length);
})
};
function DialogController($scope, $mdDialog) {
var attendee = this;
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.save = function(response) {
$mdDialog.hide(response);
};
}
}]);
and the code for the controller after separation:
myApp.controller('RegistrationController', ['$scope','$routeParams','$rootScope','$location','$filter','$mdDialog','Attendees', function($scope, $routeParams, $rootScope, $location, $filter, $mdDialog, Attendees){
...
$scope.attendees= Attendees.list();
$scope.addAttendee = function (ev) {
Attendees.add(ev);
}
$scope.deleteAttendee = function (id) {
Attendees.delete(id);
}
}]);
New service code looks like:
myApp.service('Attendees', ['$mdDialog', function ($mdDialog) {
//to create unique attendee id
var uid = 1;
//attendees array to hold list of all attendees
var attendees = [{
id: 0,
firstName: "",
lastName: "",
email: "",
phone: ""
}];
//add method create a new attendee
this.add = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'views/regForm.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
controllerAs: 'attendee',
fullscreen: this.customFullscreen, // Only for -xs, -sm breakpoints.
//locals: {parent: $scope}
})
.then(function(response){
attendees.push(response);
console.log(attendees);
console.log(attendees.length);
})
};
//simply search attendees list for given id
//and returns the attendee object if found
this.get = function (id) {
for (i in attendees) {
if (attendees[i].id == id) {
return attendees[i];
}
}
}
//iterate through attendees list and delete
//attendee if found
this.delete = function (id) {
for (i in attendees) {
if (attendees[i].id == id) {
attendees.splice(i, 1);
}
}
}
//simply returns the attendees list
this.list = function () {
return attendees;
}
function DialogController($mdDialog) {
this.hide = function() {
$mdDialog.hide();
};
this.cancel = function() {
$mdDialog.cancel();
};
this.save = function(response) {
$mdDialog.hide(response);
};
}
}]);
but I'm not able to "save" from the spawned mdDialog box which uses ng-click=save(attendee) neither close the dialog box.
What I'm doing wrong?
I'm not able to "save" from the spawned mdDialog box which uses ng-click=save(attendee) neither close the dialog box.
When instantiating a controller with "controllerAs" syntax, use the name with which it is instantiated:
<button ng-click="ctrl.save(ctrl.attendee)">Save</button>
this.add = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'views/regForm.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
controllerAs: ̶'̶a̶t̶t̶e̶n̶d̶e̶e̶'̶ 'ctrl',
fullscreen: this.customFullscreen, // Only for -xs, -sm breakpoints.
//locals: {parent: $scope}
})
.then(function(response){
attendees.push(response);
console.log(attendees);
console.log(attendees.length);
return response;
});
To avoid confusion, choose a controller instance name that is different from the data names.
$scope is not available to be injected into a service when it's created. You need to refactor the service and its methods so that you don't inject $scope into it and instead pass the current scope to the service methods when you call them.
I actually have a notification module that I inject which uses $mdDialog. Below is the code for it. Perhaps it will help.
(() => {
"use strict";
class notification {
constructor($mdToast, $mdDialog, $state) {
/* #ngInject */
this.toast = $mdToast
this.dialog = $mdDialog
this.state = $state
/* properties */
this.transitioning = false
this.working = false
}
openHelp() {
this.showAlert({
"title": "Help",
"textContent": `Help is on the way for ${this.state.current.name}!`,
"ok": "OK"
})
}
showAlert(options) {
if (angular.isString(options)) {
var text = angular.copy(options)
options = {}
options.textContent = text
options.title = " "
}
if (!options.ok) {
options.ok = "OK"
}
if (!options.clickOutsideToClose) {
options.clickOutsideToClose = true
}
if (!options.ariaLabel) {
options.ariaLabel = 'Alert'
}
if (!options.title) {
options.title = "Alert"
}
return this.dialog.show(this.dialog.alert(options))
}
showConfirm(options) {
if (angular.isString(options)) {
var text = angular.copy(options)
options = {}
options.textContent = text
options.title = " "
}
if (!options.ok) {
options.ok = "OK"
}
if (!options.cancel) {
options.cancel = "Cancel"
}
if (!options.clickOutsideToClose) {
options.clickOutsideToClose = false
}
if (!options.ariaLabel) {
options.ariaLabel = 'Confirm'
}
if (!options.title) {
options.title = "Confirm"
}
return this.dialog.show(this.dialog.confirm(options))
}
showToast(toastMessage, position) {
if (!position) { position = 'top' }
return this.toast.show(this.toast.simple()
.content(toastMessage)
.position(position)
.action('OK'))
}
showYesNo(options) {
options.ok = "Yes"
options.cancel = "No"
return this.showConfirm(options)
}
uc() {
return this.showAlert({
htmlContent: "<img src='img\\underconstruction.jpg'>",
ok: "OK",
title: "Under Construction"
})
}
}
notification.$inject = ['$mdToast', '$mdDialog', '$state']
angular.module('NOTIFICATION', []).factory("notification", notification)
})()
Then inject notification (lower case) into my controllers in order to utilize it. I store notification in a property of the controller and then call it with something like this:
this.notification.showYesNo({
clickOutsideToClose: true,
title: 'Delete Customer Setup?',
htmlContent: `Are you sure you want to Permanently Delete the Customer Setup for ${custLabel}?`,
ariaLabel: 'Delete Dialog'
}).then(() => { ...
this.notification.working = true
this.ezo.EDI_CUSTOMER.remove(this.currentId).then(() => {
this.primaryTab = 0
this.removeCustomerFromList(this.currentId)
this.currentId = 0
this.notification.working = false
}, error => {
this.notification.working = false
this.notification.showAlert({
title: "Error",
htmlContent: error
})
})

Mocking $uibModal's opened and closed promises

I am using Angular-UI's $uibModal to open a modal in my code. After calling the open method, I defined code to run in the opened.then() & closed.then() promises. All of this works fine, but when trying to test it (in Jasmine), I can't figure out how to resolve the promises for opened and closed.
here is the code I use to open the modal (in my controller):
function backButtonClick() {
var warningModal = $uibModal.open({
animation: true,
ariaLabelledBy: 'modal-warning-header',
ariaDescribedBy: 'modal-alert-body',
backdrop: 'static',
templateUrl: 'app/components/directives/modals/alertModal/alertModal.html',
controller: 'AlertModalController',
controllerAs: 'vm',
size: 'sm',
resolve: {
options: function() {
return {
title: stringsService.getString('WorkNotSavedTitle'),
message: stringsService.getString('WorkNotSavedMessage'),
modalHeaderClass: 'modal-warning-header',
modalHeaderIconClass: 'fa-warning modal-warning-alert-icon',
modalHeaderTitleClass: 'modal-warning-alert-title',
modalContentClass: 'modal-warning-content',
modalButtonsClass: 'modal-centered-buttons',
showModalHeader: true,
showPrimaryButton: true,
showSecondaryButton: false,
showTertiaryButton: true,
primaryButtonText: stringsService.getString('RemainInActivityButton'),
primaryButtonClick: function() { warningModal.dismiss(); },
tertiaryButtonText: stringsService.getString('LeaveActivityButton'),
tertiaryButtonClick: function() { warningModal.dismiss(); leaveActivity(); }
};
}
}
});
warningModal.opened.then(function() { vm.isWarningModalOpen = true; });
warningModal.closed.then(function() { vm.isWarningModalOpen = false; });
}
and the test I have so far:
it('should show the Warning modal if the back button is clicked', function() {
var modalServiceMock = {
open: function(options) {}
};
sinon.stub(modalServiceMock, 'open').returns({
dismiss: function() { return; },
opened: {
then: function(callback) { return callback(); }
},
closed: {
then: function(callback) { return callback(); }
}
});
var ctlr = $controller('BayServiceController', { $scope: this.$scope, $uibModal: modalServiceMock});
ctlr.backButtonClick();
//this line passes
expect(modalServiceMock.open).toHaveBeenCalled();
//this line fails
expect(ctlr.isWarningModalOpen).toBe(true);
});
Ok, so there may have been a better way about it, but this seems to work so here's what I came up with.
it('should show the Warning modal if the back button is clicked', function() {
modalServiceMock = {
open: function(modalOptions) {
var closedCallback;
return {
dismiss: function() { closedCallback(); },
opened: {
then: function(callback) { callback(); }
},
closed: {
then: function(callback) { closedCallback = callback; }
},
resolver: modalOptions.resolve
};
}
};
var ctlr = $controller('BayServiceController', { $scope: this.$scope, $uibModal: modalServiceMock});
ctlr.backButtonClick();
this.rootScope.$apply();
expect(ctlr.isWarningModalOpen).toBe(true); //this now passes
//to test closing the modal, I access the resolver property of the mock and run the given method for dismissing the modal
ctlr.warningModal.resolver.options().primaryButtonClick();
expect(ctlr.isWarningModalOpen).toBe(false);
});

AngularJs UI Grid rebind from Modal

I have a main controller in which I load data into a "angular-ui-grid" and where I use a bootstrap modal form to modify detail data, calling ng-dlbclick in a modified row template :
app.controller('MainController', function ($scope, $modal, $log, SubjectService) {
var vm = this;
gridDataBindings();
//Function to load all records
function gridDataBindings() {
var subjectListGet = SubjectService.getSubjects(); //Call WebApi by a service
subjectListGet.then(function (result) {
$scope.resultData = result.data;
}, function (ex) {
$log.error('Subject GET error', ex);
});
$scope.gridOptions = { //grid definition
columnDefs: [
{ name: 'Id', field: 'Id' }
],
data: 'resultData',
rowTemplate: "<div ng-dblclick=\"grid.appScope.editRow(grid,row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" ui-grid-cell></div>"
};
$scope.editRow = function (grid, row) { //edit row
$modal.open({
templateUrl: 'ngTemplate/SubjectDetail.aspx',
controller: 'RowEditCtrl',
controllerAs: 'vm',
windowClass: 'app-modal-window',
resolve: {
grid: function () { return grid; },
row: function () { return row; }
}
});
}
});
In the controller 'RowEditCtrl' I perform the insert/update operation and on the save function I want to rebind the grid after insert/update operation. This is the code :
app.controller('RowEditCtrl', function ($modalInstance, $log, grid, row, SubjectService) {
var vm = this;
vm.entity = angular.copy(row.entity);
vm.save = save;
function save() {
if (vm.entity.Id === '-1') {
var promisePost = SubjectService.post(vm.entity);
promisePost.then(function (result) {
//GRID REBIND ?????
}, function (ex) {
$log.error("Subject POST error",ex);
});
}
else {
var promisePut = SubjectService.put(vm.entity.Id, vm.entity);
promisePut.then(function (result) {
//row.entity = angular.extend(row.entity, vm.entity);
//CORRECT WAY?
}, function (ex) {
$log.error("Subject PUT error",ex);
});
}
$modalInstance.close(row.entity);
}
});
I tried grid.refresh() or grid.data.push() but seems that all operation on the 'grid' parameter is undefinied.
Which is the best method for rebind/refresh an ui-grid from a bootstrap modal ?
I finally solved in this way:
In RowEditCtrl
var promisePost = SubjectService.post(vm.entity);
promisePost.then(function (result) {
vm.entity.Id = result.data;
row.entity = angular.extend(row.entity, vm.entity);
$modalInstance.close({ type: "insert", result: row.entity });
}, function (ex) {
$log.error("Subject POST error",ex);
});
In MainController
modalInstance.result.then(function (opts) {
if (opts.type === "insert") {
$log.info("data push");
$scope.resultData.push(opts.result);
}
else {
$log.info("not insert");
}
});
The grid that received inside RowEditCtrl is not by reference, so it wont help to refresh inside the RowEditCtrl.
Instead do it right after the modal promise resolve in your MainController.
like this:
var modalInstance = $modal.open({ ...});
modalInstance.result.then(function (result) {
grid.refresh() or grid.data.push()
});

Unable to watch/observe scope?

<button-large color="green" click="createWorkstation()" busy="disableSave()" busyLabel="Saving...">Save</button-large>
I'm not able to watch changes to the output of disableSave(). The console.log()'s shown in my directive are never triggered when the output of .busy is changed. What am I doing wrong?
directive('buttonLarge', function () {
return {
scope: {
busy: '&',
click: '&'
},
replace: true,
restrict: 'E',
transclude: true,
template: '<button class="buttonL" ng-transclude/>',
link: function (scope, element, attrs) {
//when the button is busy, disable the button
if (angular.isDefined(scope.busy())) {
scope.$watch(scope.busy(), function () {
console.log('watched');
});
attrs.$observe(scope.busy(), function () {
console.log('observed');
});
}
//setup click event - https://groups.google.com/forum/#!topic/angular/-uVE5WJWwLA
if (angular.isDefined(scope.click)) {
element.bind('click', scope.click);
}
}
}
})
Controller
$scope.newWorkstationDialog = function (workflowProcess) {
var d = $dialog.
dialog({
resolve: {
workflowProcess: function () {
return workflowProcess;
}
}
}).
open('/partials/admin/'+workflowProcess.entity.slug+'/setup.htm', ['$scope', 'dialog', ..., function ($scope, dialog, ...) {
$scope.saving = false;
/* Create the workstation */
$scope.createWorkstation = function () {
console.log('saving');
$scope.saving = true;
$timeout(function () {
$scope.saving = false;
console.log('stopped saving');
}, 1000);
}
//Should the save button be disabled?
$scope.disableSave = function () {
return $scope.saving;//|| $scope.form.$valid;
}
$scope.cancel = function () {
dialog.close();
}
}]);
}
Your syntax of watching in not correct .You should be not using scope when doing watch because internally it use $parse service which internally attach scope . So you need to modify your code as below
1st option
scope.$watch(function(){
return scope.busy()
}, function (newvalue,oldvalue) {
console.log('watched');
});
2nd option
scope.$watch('busy()', function (newvalue,oldvalue) {
console.log('watched');
});

Resources