Angular UI Modal causes Infinite Digest Loop - javascript

I have been struggling with creating a system to allow articles to be retrieved and opened in a modal pop-up window. It has been implemented successfully using the Bootstrap modal, but due to some new requirements I need to convert to using the Angular UI Modal.
I think the issue is stemming from my handling of URL changes by Angular's $location.search(), but I can't pinpoint it.
Since adding the $uibModal.open() call, this infinite digest loop occurs whenever I click on an article, this launching the openModal function in my controller.
I will include my controller code and the error message I receive below. The two points of entry to the controller are near the bottom at the $rootScope.$on and $scope.$watch calls. They allow the modal to respond to changes in the URL.
The end goal is the ability to open an Angular UI modal when the URL changes, so that I can remove the URL params when the modal is dismissed.
Thanks for any help!
My controller:
(function () {
'use strict';
//Create the LinkModalController and bind it to the core app. This makes it always available.
angular
.module('app.core')
.controller('LinkModalController', LinkModalController);
LinkModalController.$inject = ['$location', '$q', '$rootScope', '$scope', '$uibModal', 'contentpartservice', 'logger'];
/* #ngInject */
function LinkModalController($location, $q, $rootScope, $scope, $uibModal, contentpartservice, logger) {
var vm = this;
/*--------------Variable Definitions--------------*/
vm.modalData = {};
vm.isModalLoading = true;
vm.selectedTab;
vm.urlHistory;
/*--------------Function Definitions--------------*/
vm.selectTab = selectTab;
vm.openModal = openModal;
/*Activate Controller*/
activate();
/*--------------Functions--------------*/
/*Announcement clicks are handled separately because the announcement data contains the full article*/
function handleAnnouncementClick(data) {
vm.modalData = data;
$("#announcementModal").modal();
return;
}
/*Set the active tab for the open modal*/
function selectTab(tab) {
vm.selectedTab = tab;
return;
}
/*Clicking an article of any content type should be funneled through this function. Eventually to be merged with handleSearchResultClick*/
function handleContentTypeClick(data) {
setUrl(data.id, data.contentType.value);
return;
}
function handleUrlParamsModalLaunch(data) {
console.log('launching modal');
/*Ensure modal is not displaying any data*/
vm.modalData = {};
vm.selectedTab = null;
/*Show modal loading screen*/
vm.isModalLoading = true;
var modalInstance = $uibModal.open({
templateUrl: 'app/modals/contentTypeModalTemplate.html',
controller: 'LinkModalController as vm',
});
/*Call the content service to return the clicked content article*/
contentpartservice.getContentItem(data.id, data.type).then(function (contentItem) {
if (contentItem) {
vm.isModalLoading = false;
vm.modalData = contentItem;
return;
} else {
closeModal("#contentPartModal").then(function () {
vm.isModalLoading = false;
logger.error('An error occurred while fetching content');
});
return;
}
}, function (error) {
closeModal("#contentPartModal").then(function () {
vm.isModalLoading = false;
logger.error('An error occurred while fetching content');
});
return;
});
}
/*Close a modal and return a promise object - This allows other code to be executed only after the modal closes*/
function closeModal(modalId) {
$(modalId).modal('hide');
var defer = $q.defer();
defer.resolve();
return defer.promise;
}
//Function to append information to the URL required to retrieve the displayed article
function setUrl(contentId, contentType) {
var urlParams = $location.search();
if (urlParams.q) {
$location.search({ q: urlParams.q, type: contentType, id: contentId });
} else {
$location.search({ type: contentType, id: contentId });
}
console.log($location.search());
return;
}
/*Route link click calls to handle different data structures*/
function openModal(data, context) {
switch (context) {
case 'urlParams':
handleUrlParamsModalLaunch(data);
break;
case 'announcement':
handleAnnouncementClick(data);
break;
case 'contentType':
handleContentTypeClick(data);
break;
default:
logger.error('An error occurred while fetching content');
}
return;
}
/*--------------Listeners--------------*/
/*Catch links click events broadcast from the $rootScope (shell.controller.js)*/
$rootScope.$on('openModal', function (event, data, context) {
vm.openModal(data, context);
return;
});
/*--------------Activate Controller--------------*/
function activate() {
/*Create a watcher to detect changes to the URL*/
$scope.$watch(function () { return $location.search() }, function () {
alert('url changed');
/*Wait for modals to render*/
var urlParams = $location.search();
if (urlParams.type && urlParams.id) {
vm.openModal(urlParams, 'urlParams');
}
/*Handle the inital page load. (Must wait until content is loaded to open modal). This code only runs once.*/
$rootScope.$on('$includeContentLoaded', function () {
alert('url changed first laod');
/*Wait for modals to render*/
var urlParams = $location.search();
if (urlParams.type && urlParams.id) {
vm.openModal(urlParams, 'urlParams');
}
});
}, true);
}
}
})();
The error message that was logged is a massive block of text, so I've pasted it into a Google Doc: https://docs.google.com/document/d/1esqZSMK4_Tiqckm-IjObqTvMGre2Ls-DWrIycvW5CKY/edit?usp=sharing

don't know if you have tried $locationProvider.html5Mode(true); in your app's config module. If you use jquery model to open the popup, it might have conflict between angular and jquery because jquery also watches the change on the url. I used to have similar issue like this.

Related

UI not updating when mdDialog calls parent controller function

Hi Im having an issue where im showing a mdDialog from Angular Material and using my directives controller as the controller of the dialog so i can call a specific function without having to pass stuff back and add in extra steps to the code. The function gets called successfully but the UI is not updated when the function successfully ends. Wondering if anyone can see where im going wrong with this.
Assume for now that the first if statement is true.
Dialog call
this.showImageUploadModal = function() {
$mdDialog.show({
clickOutsideToClose: true,
scope: $scope, // use parent scope in template
preserveScope: true, // do not forget this if use parent scope
templateUrl: 'app/directives/modals/upload-files-modal.html',
controller: MessagingController,
controllerAs: 'controller'
});
};
Function being called but not updating UI
this.addAttachment = function() {
console.log("sending attachment");
var ref = this;
var note = this.user.first_name + " has attached a file.";
if($state.current.name === 'inbox') {
MessagingService.createMessage(this.convo.id, note, this.userUploadedNoteFiles).then(
function success(response) {
console.log("Inbox attachment sent", response);
ref.convo.messages.push(response.data);
console.log(ref.convo.messages);
// ref.viewableNoteFiles = [];
},
function failure(response) {
$mdToast.show(
$mdToast.simple().
textContent("Failed to send the message please try again.").
theme('error-toast'));
}
);
} else if (this.notes === 'true') {
TicketingService.addNote($stateParams.id, note, this.userUploadedNoteFiles).then(
function success(response) {
console.log("Notes attachment sent", response);
ref.convo.messages.push(response.data);
// ref.viewableNoteFiles = [];
},
function failure(response) {
$mdToast.show(
$mdToast.simple().
textContent("Failed to send the message please try again.").
theme('error-toast'));
}
);
} else if(this.contractor === 'true') {
TicketingService.createMessage($stateParams.id, this.convo.id, note, this.userUploadedNoteFiles).then(
function success (response) {
console.log("Contractor attachment sent", response);
ref.convo.messages.push(response.data);
},
function failure () {
$mdToast.show(
$mdToast.simple().
textContent("Failed to upload the file attachments").
theme('error-toast'));
}
);
}
};
In the end i found i could achieve what i was looking for using Angulars $rootScope.$broadcast. to broadcast the return data back to the controller that needed it.
Im not sure this is the right way to do it but it works.

Show confirmation modal before calling $routeChangeStart in AngularJs like window onbeforeunload

Im able to show a confirmation modal once route starts to change, if users selects to stay my route does not change, it stays to the original route, but loads the form directives again, which causes form to loss all its checkbox, input values. It gets reset to defaults.
If a user closes the page, i'm able to show confirmation modal, also the form state does not change. All values are retained.
Below is my code:
also, please note Im also injecting a resolve for all routes by default (this Angular : How use one resolve for all the routes of my application)
After that im calling .run()
$rootScope.$on('$routeChangeStart', function (event, newUrl, oldUrl) {
//isLoggedIn also check URL params
if (!Auth.isLoggedIn()) {
$window.location.href = Auth.getLoginUrl();
}
////unsaved modal start
if ($rootScope.unsaved) {
ngDialog.open({
className: 'ngdialog-theme-default unsaved-modal',
template: 'scripts/core/commonmodal/tplUnsavedModal.html',
controller: [function OpenDialogContainer() {
var modal = this;
modal.message = 'You have some unsaved changes. Do you want to leave this page?';
modal.stop = function () {
modal.processing = true;
ngDialog.close();
$rootScope.$broadcast('$routeChangeSuccess');
};
modal.continue = function () {
modal.processing = true;
ngDialog.close();
$rootScope.unsaved = false;
$location.path(newUrl.$$route.originalPath); //Go to page they're interested in
};
}],
controllerAs: 'modal'
});
//prevent navigation by default since we'll handle it
//once the user selects a dialog option
event.preventDefault();
}
});
Im setting $rootScope.unsaved = true if form is NOT $pristine and NOT $submitted
As you can see in the below gifvideo, on stay the route runs the controller function again. Instead what I wanted was a window onbeforeunload alike effect.
http://recordit.co/g5T9wWkDry.gif
I fixed it just by removing this line $rootScope.$broadcast('$routeChangeSuccess'); also, instead I made a directive.
link: function($scope) {
var message = 'You have some unsaved changes. Do you want to leave this page?';
$window.onbeforeunload = function(){
if ($scope.unsavedChanges) {
return 'You have some unsaved changes. Do you want to leave this page?';
}
};
var $routeChangeStartUnbind = $rootScope.$on('$routeChangeStart', function(event, newUrl) {
if ($scope.unsavedChanges) {
$rootScope.pageloaded = true;//prevent loading icon
ngDialog.open({
appendClassName: 'unsaved-modal',
template: 'scripts/core/commonmodal/tplUnsavedModal.html',
controller: [function OpenDialogContainer() {
var modal = this;
modal.message = message;
modal.stop = function () {
modal.processing = true;
ngDialog.close();
};
modal.continue = function () {
modal.processing = true;
ngDialog.close();
$routeChangeStartUnbind();
$location.path(newUrl.$$route.originalPath); //Go to page they're interested in
$rootScope.pageloaded = false;
$scope.unsavedChanges = false;
$window.location.reload();//$route.reload() does not reload services
};
}],
controllerAs: 'modal'
});
//prevent navigation by default since we'll handle it
//once the user selects a dialog option
event.preventDefault();
}
});
$scope.$on('$destroy', function() {
window.onbeforeunload = null;
$routeChangeStartUnbind();
});
}

Show loading overlay until $http get images are loaded

I want to show a loading animation (ideally that shows % of how much is loaded) whilst content loads from my $http get.
I have made an attempt, but it does not seem to hide the content I am trying to hide.
I set a time length- but I do not want it to show the loading overlay for a set time. I want it to show the loading overlay (possibly until a minimum of 3 images are loaded?) until the element is loaded.
Here is my attempt in a plunker:
http://plnkr.co/edit/7ScnGyy2eAmGwcJ7XZ2Z?p=preview
.factory('cardsApi', ['$http', '$ionicLoading', '$timeout', function ($http, $ionicLoading, $timeout) {
var apiUrl = 'http://mypage.com/1/';
$ionicLoading.show({
duration: 3000,
noBackdrop: true,
template: '<p class="item-icon-left">Loading stuff...<ion-spinner icon="lines"/></p>'
});
var getApiData = function () {
return $http.get(apiUrl).then($ionicLoading.hide, $ionicLoading.hide);
};
return {
getApiData: getApiData,
};
}])
.controller('CardsCtrl', ['$scope', 'TDCardDelegate', 'cardsApi', '$http',
function ($scope, TDCardDelegate, cardsApi, $http) {
$scope.cards = [];
cardsApi.getApiData()
.then(function (result) {
console.log(result.data) //Shows log of API incoming
$scope.cards = result.data;
$scope.product_id = result.data.product_id;
})
.catch(function (err) {
//$log.error(err);
})
Remove the duration line from your $ionicLoading.show declaration.
duration: 3000,
So that it looks like:
$ionicLoading.show({
noBackdrop: true,
template: '<p class="item-icon-left">Loading stuff...<ion-spinner icon="lines"/></p>'
});
And that should work (at least it does in the plunker). The duration property specifies when to close the ionicLoading instance and does not wait for ionicLoading.hide().
You want to wait until the image is actually loaded and rendered, but you are hiding the loading messages as soon as the API call returns. From your code it looks as though the API returns the image URL, not the image data itself?
In which case you could do it using the element.onload(), however the problem with this is that it's no longer a generic API which works for loading anything but I'll let you decide whether that's OK for your use case.
var imagesLoaded = 0;
var loadImage = function(result) {
var image = new Image();
image.onload = function () {
imagesLoaded++;
if (imagesLoaded >= 3)
$ionicLoading.hide();
};
// We still want to hide the loading message if the image fails to load - 404, 401 or network timeout etc
image.onerror = function () {
imagesLoaded++;
if (imagesLoaded >= 3)
$ionicLoading.hide();
};
image.src = result.image_url;
};
// We still want to hide the loading message if the API call fails - 404, 401 or network timeout etc
var handleError = function() {
imagesLoaded++;
if (imagesLoaded >= 3)
$ionicLoading.hide();
};
var getApiData = function () {
return $http.get(apiUrl).then(loadImage, handleError);
};

Angularjs data binding issue / javascript being weird

This is undoubtedly a stupid problem where I'm just doing something simple wrong.
I have a page with several directives, loading their templates and controllers. All of which is working fine except for this one.
Using the controller as model, this. is the same as $scope.. So in my controller I have:
var self = this;
this.states = { showControls: false, showVideo: false }
this.showVideo = function() { self.states.showVideo = true; }
this.showControls = function() { self.states.showControls = true; }
$scope.$on(Constants.EVENT.START_WEBCAM, self.showVideo)
$scope.$on(Constants.EVENT.VIDEO_SUCCESS, self.showControls)
In the view I have a button to reveal this part of the view and subsequently request access to your webcam. Clicking the button broadcasts an event with $rootScope.$broadcast from the parent controller.
When the user grants access to the webcam (handled in the directive's link function) it broadcasts another event the same way.
Both methods are triggered by listening with $scope.$on, and both methods fire as they should. However, the showVideo method successfully updates its associated state property, and the showControls method does not. What am I doing wrong?
Using the debug tool it looks like states.showControls is being set to true, but this change isn't reflected in the view, and adding a watcher to the states object doesn't detect any change at this point either. It does when I set showVideo.
EDIT
This part is in the directive:
if (Modernizr && Modernizr.prefixed('getUserMedia', navigator)) {
userMedia = Modernizr.prefixed('getUserMedia', navigator);
}
var videoSuccess = function(stream) {
// Do some stuff
$rootScope.$broadcast(Constants.EVENT.VIDEO_SUCCESS);
}
scope.$on(Constants.EVENT.START_WEBCAM, function() {
if (MediaStreamTrack && MediaStreamTrack.getSources) {
MediaStreamTrack.getSources(function(sourceInfo) {
var audio = null;
var video = null;
_.each(sourceInfo, function(info, i) {
if (info.kind === "audio") {
audio = info.id;
} else if (info.kind === "video") {
video = info.id;
} else {
console.log("random unknown source: ", info);
}
});
if (userMedia) { userMedia(getReqs(), videoSuccess, error); }
});
}
});

Angular Js $scope

When establishing a controller, and setting the $scope to use a factory method (for GETs and POSTs), during the page load process, my POSTs are fired. Below is an example of the code. To fix this, I wrapped the "POST" in a jQuery click event function and everything works smoothly. Below is the code.
In the controller (app.js):
demoApp.controller('SimpleController', function ($scope, simpleFactory) {
$scope.customers = [];
init();
function init() {
$scope.departments = simpleFactory.getDepartments();
}
// Works fine
$('#myButton').click(function () {
simpleFactory.postDepartments();
});
// When setting the "scope" of a controller, during page load the scope factory method is fired off!
// seems like a defect.
//$scope.addDepartment = simpleFactory.postDepartments();
});
So, what is going on here is that if I uncomment the $scope.addDepartment = ... on page load, the postDepartments() factory method is called. This is not the desired behavior. Here is how I have the Html Dom element wired:
<button id="myButton" data-ng-click="addDepartment()">Add Department</button>
So, if I uncomment, like I said above, it adds the department before the user even clicks the button. However, approaching it the jQuery way, there is no issue.
Is this a known bug? Is this the intended functionality? Also, see the factory below, maybe the problem is there?
demoApp.factory('simpleFactory', function ($http) {
var departments = [];
var factory = {};
factory.getDepartments = function () {
$http.get('/Home/GetDepartments').success(function (data) {
for (var i = 0; i < data.length; i++) {
departments.push({ desc: data[i].desc, id: data[i].id });
}
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
return departments;
};
factory.postDepartments = function () {
$http.post('/Home/PostDepartment', {
cName: 'TST',
cDescription: 'Test Department'
}).success(function (data) {
departments.push({ desc: 'Test Department', id: departments.length + 1 });
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
return departments;
};
return factory;
});
Try this:
$scope.addDepartment = function() {
return simpleFactory.postDepartments();
}
This will also allow you to pass in arguments in the future, should you decide to. The way you originally had it, you were both assigning the function and calling it at the same time.
Then, you can use it in ngClick:
<button ng-click="addDepartment()">Add Department</button>
Don't use the jQuery click method in your controller, it defeats the purpose of separating the concerns into models, views, controllers, etc. That's what directives are for.

Categories