angular $uibModalStack.dismissAll() doesn't work - angularjs

I have the following controller: when routed into it, I show a modal popup "Wait" with no buttons. While the popup is on, I do an http call that returns data. I want to close the popup somehow at this point, no buttons. I've tried a variety of things without a success. My experiments gave me these 2 no-error options:
$scope.popup.close('a');
$uibModalStack.dismissAll();
Unfortunately they don't work, the popup remains to be on. Much appreciate some help here. Here is what I have for the controller:
app.controller('PreviewCtrl', function($scope, $rootScope, $log, $location, $injector, $uibModal, $uibModalStack, cropService) {
var service = $injector.get('previewImageService');
$scope.crop = service.getProperty();
$log.info("PreviewCtrl --ln 1353 crop:", $scope.crop);
if($scope.crop == null){
$location.path("/edit");
}
var prefix = '${binding.variables.awsCropFolder}'+"/"+$scope.crop.name+"/"+$rootScope.imgName;
$scope.srcPreview = null;
$scope.popup = $uibModal.open({
animation: true,
templateUrl: 'progress.html',
ariaDescribedBy: 'modal-body',
size: "sm"
});//backdrop: "static",
$scope.getImage = function () {
var promise = cropService.getCrop(prefix);
promise.then(
function(payload) {
//console.log("payload:", payload)
$scope.srcPreview = payload.data.src == "" ? null:payload.data.src;
},
function(errorPayload) {
$log.error('Promise failure', errorPayload);
}
);
console.log("POPUP", $scope.popup );
$scope.popup.close('a');
$uibModalStack.dismissAll();
};
$scope.getImage();
$scope.returnToEdit = function () {
$location.path("/edit");
};
});

For anyone who runs into the same issue - I replaced the modal popup with jquery one: http://dev.vast.com/jquery-popup-overlay/
And it works works! Steps:
1) download + install jquery.popupoverlay.js
2) add your popup:
<div id="my_popup">
<div class="modal-body" style="background-color:#ffffff;margin:0px 5px 0px 8px;">
<img height="10" width="150" src="/resources/images/imageTool/progress.gif" alt="Progress Bar"/>
</div>
</div>
3) Add logic to open and close it:
$scope.getImage = function () {
var popUp = $('#my_popup');
popUp.popup('show');
var promise = cropService.getCrop(prefix,null);
promise.then(
function(payload) {
//console.log("payload:", payload)
$scope.srcPreview = payload.data.src_1 == "" ? null:payload.data.src_1;
setTimeout(function (){popUp.popup('hide')}, 4500);
},
function(errorPayload) {
$log.error('Promise failure', errorPayload);
}
);
};
I'd like to use an angular popup, but for now, what I have will have to do.

Related

How to record video and Audio in angularJS mobile Website

I am developing a mobile website using Express and AngularJS.
I want to show a modal to the user to record a video and then save it in a folder.
I tried using RecordRTC, this is my code:
video.partial.html
<script src="./../../node_modules/recordrtc/RecordRTC.js"></script>
<div ng-controller="index">
<button ng-click="addVideo()">Add Video</button>
</div>
app.js
var app = angular.module('myApp', ['ngRoute', 'ngMaterial', 'ui.bootstrap']);
app.controller('index', ['$scope', '$location', 'Storage', '$http', '$modal', '$sce', function ($scope, $location, Storage, $http, $modal, $sce) {
$scope.addVideo = function () {
console.log('adding Video');
$scope.openVideoModal();
};
$scope.openVideoModal = function (data) {
$scope.modalInstance = $modal.open({
templateUrl: 'partials/video.modal.html',
controller: 'index',
resolve: {
data: function () {
return data === null ? {} : data;
}
}
}).result.then(function () { }, function (res) { });
};
}
video.modal.html
<style>
html,
body {
margin: 0!important;
padding: 0!important;
overflow: hidden!important;
width: 100%;
}
</style>
<div class="modal-header">
<h4 class="modal-title">Record Video</h4>
</div>
<div style="margin: 5%;">
<button class="md-raised md-primary" id="btn-start-recording">Start Recording</button>
<button class="md-raised md-primary" id="btn-stop-recording">Stop Recording</button>
<hr>
<video controls autoplay style: "width: 100%"></video>
</div>
<script>
console.log('script is called here');
var recorder; // globally accessible
var btnStart = document.getElementById('btn-start-recording');
var btnStop = document.getElementById('btn-stop-recording');
var video = document.querySelector('video');
function captureCamera(callback) {
navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(function (camera) {
console.log('capture camera');
callback(camera);
}).catch(function (error) {
alert('Unable to record Video.');
console.error(error);
});
};
function stopRecordingCallback() {
console.log('stop recording');
video.src = video.srcObject = null;
video.src = URL.createObjectURL(recorder.getBlob());
video.play();
recorder.camera.stop();
recorder.destroy();
recorder = null;
};
btnStart.onclick = function () {
this.disabled = true;
console.log('start recording');
captureCamera(function (camera) {
setSrcObject(camera, video);
video.play();
recorder = RecordRTC(camera, {
type: 'video'
});
recorder.startRecording();
// release camera on stopRecording
recorder.camera = camera;
btnStop.disabled = false;
});
};
btnStop.onclick = function () {
console.log('stopping recording');
this.disabled = true;
recorder.stopRecording(stopRecordingCallback);
btnStart.disabled = false;
};
</script>
But now, the script from the modal does not load when the modal is shown, and thus clicking the start recording button does nothing.
Is there some way to fix this? or, is there a better way to record audio and video in AngularJS?
Any suggestions would be helpful!

Adding auto refresh after a particular interval (5 seconds) in angular js

I have a page in which which has multiple tabs. I want to add the feature that the tab is reloaded automatically after a fixed duration. I have the following:
<uib-tab index="$index + 1" ng-repeat="environmentRegionTab in ctrl.environmentRegionTabs"
heading="{{environmentRegionTab.environmentRegionName}}"
select="ctrl.onEnvironmentRegionSelect(environmentRegionTab.id);">
<div class="panel-body tab-content">
<div class="alert alert-success" ng-show="ctrl.deployStatus[ctrl.environmentRegion.name].show">
<strong>Launched deployment with execution id
{{ctrl.deployStatus[ctrl.environmentRegion.name].id}}</strong>
</div>
...................
And the following controller:
export function ServiceDetailController(ecsServiceResponse, teamListResponse, productListResponse, businessSubOwnerListResponse, serviceInstancesResponse, businessOwnerListResponse, EcsService, SecretsService, $location, $stateParams, $uibModal, $scope, $state, $window) {
'ngInject';
var self = this;
var serviceInstanceId;
self.ecsAuthControl = {};
self.initialize = _initialize;
self.clearMessages = _clearMessages();
self.onEnvironmentRegionSelect = _onEnvironmentRegionSelect;
$scope.reloadRoute = function() {
$state.reload();
};
function _onEnvironmentRegionSelect(serviceInstanceId) {
self.selectedserviceInstanceId = serviceInstanceId;
if (serviceInstanceId) {
$location.search('serviceInstanceId', serviceInstanceId);
_loadEnvironmentRegion();
} else {
$location.search('serviceInstanceId', null);
_loadSummary();
}
}
}
I am not able to understand how to add the fixed time duration? I also would like to show a counter ticking down from 5 to 0 after which the page is reloaded. How can I do it? I declared the reload function but I am not able to figure out how to add a fixed timer? Thanks!
Make use of $interval service in angularjs:
$interval(function () {
$scope.reloadRoute();
}, 5000);
(make sure to pass $interval as a dependency to controller)
Example Plunker
Here is one of the safest way through which you can achieve the functionality.
Function which does the refresh:-
var poll = function() {
console.log("polling");
$scope.doRefresh(); // Your refresh logic
};
Call the poll from StartPollar:
var startPoller = function() {
if (angular.isDefined(stop)) {
stopPoller();
}
stop = $interval(poll, $scope.intervalTime); //$scope.intervalTime : refresh interval time
};
If you want to Stop it:
var stopPoller = function() {
if (angular.isDefined(stop)) {
$interval.cancel(stop);
stop = undefined;
console.log("cancelled poller operation");
} else {
console.log("do nothing");
}
};

Angular modal service closing issue

I am using angular modal service to show incoming call popup.
Everything seems to work but in particular case the popup closes leaving behind grey overlay blocking the whole UI.
Popup closes perfectly when i manually click reject and close button provided in popup but gives unusual behaviour when i use timeout to close the popup whithout doing any operation on it.
For reference i am giving my whole code.
----------------------------modal popup UI code---------------------------
<div class="modal fade">
<div class="modal-dialog modal-lg modal-dialog-custom">
<div class="modal-content modal-content-dialog">
<div class="modal-header">
<audio class="incoming-videoconference-audio" autoplay loop>
<source src="../images/dataCallIncoming.mp3" type="audio/mpeg">
</audio>
<button type="button" class="close" ng-click="vm.hangUp()" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Incoming Call</h4>
</div>
<img class="incoming-nowConf-logo" src="../images/new_nowconfer_e.png" />
<div id="state" class="grid_4 alpha">
<div class="gps_ring"></div>
</div>
<div class="modal-body modal-body-custom">
<div style="text-overflow:ellipsis;overflow:hidden;" class="call-from">
{{vm.confName}}
</div>
<div class="call-control">
<button type="button"class="btn-sm btn-sm-gray cancel-btn" ng-click="vm.hangUp()" data-dismiss="modal">Reject</button>
<span style="width:50px;"> </span>
<button type="button"class="btn-sm btn-sm-green" ng-click="vm.accept()" data-dismiss="modal">Answer</button>
</div>
</div>
</div>
</div>
</div>
-------------------------modal popup controller------------------------------
(function () {
'use strict';
angular
.module('incomingModule')
.controller('IncomingCallController', IncomingCallController);
IncomingCallController.$inject = ['$scope','$rootScope','plivoclient','$routeParams','$location','close','from', 'instId','confName','$timeout'];
function IncomingCallController($scope,$rootScope , plivoclient,$routeParams ,$location,close, from, instId,confName,$timeout) {
var vm = this;
vm.connecting = false;
vm.from = from;
vm.confName = confName;
vm.dismissModal = function(result) {
plivoclient.conn.reject();
console.log('vm.dismissModal::'+result);
close(result, 200); // close, but give 200ms for bootstrap to animate
};
activate();
function activate(){
$timeout(function(){
vm.dismissModal('cancel');
},25000);
}
vm.accept = function() {
plivoclient.conn.answer();
vm.connecting = true;
console.log("incoming call accept............");
vm.dismissModal('accept');
$timeout(function(){
$location.path( "/call/"+$rootScope.id2);
},300);
};
vm.hangUp = function() {
plivoclient.conn.reject();
vm.dismissModal('reject');
console.log("incoming call hangedup............");
};
}
}());
-------------------------opening modal code----------------------------------------
ModalService.showModal({
templateUrl: '../../partials/calls.incoming.popup.html',
controller: 'IncomingCallController',
controllerAs: 'vm',
inputs: {
from: dataNew.callerName || '',
instId: dataNew.extraHeaders['X-Ph-Instid'] || dataNew.extraHeaders['X-Ph-instid'],
confName:$rootScope.conferenceData.conf_name
}
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {
//$scope.message = result ? "You said Yes" : "You said No";
});
});
----------------------------------angular modal service code----------------------------------
'use strict';
let module = angular.module('angularModalService', []);
module.factory('ModalService', ['$animate', '$document', '$compile', '$controller', '$http', '$rootScope', '$q', '$templateRequest', '$timeout',
function($animate, $document, $compile, $controller, $http, $rootScope, $q, $templateRequest, $timeout) {
function ModalService() {
var self = this;
// Returns a promise which gets the template, either
// from the template parameter or via a request to the
// template url parameter.
var getTemplate = function(template, templateUrl) {
var deferred = $q.defer();
if (template) {
deferred.resolve(template);
} else if (templateUrl) {
$templateRequest(templateUrl, true)
.then(function(template) {
deferred.resolve(template);
}, function(error) {
deferred.reject(error);
});
} else {
deferred.reject("No template or templateUrl has been specified.");
}
return deferred.promise;
};
// Adds an element to the DOM as the last child of its container
// like append, but uses $animate to handle animations. Returns a
// promise that is resolved once all animation is complete.
var appendChild = function(parent, child) {
var children = parent.children();
if (children.length > 0) {
return $animate.enter(child, parent, children[children.length - 1]);
}
return $animate.enter(child, parent);
};
self.showModal = function(options) {
// Get the body of the document, we'll add the modal to this.
var body = angular.element($document[0].body);
// Create a deferred we'll resolve when the modal is ready.
var deferred = $q.defer();
// Validate the input parameters.
var controllerName = options.controller;
if (!controllerName) {
deferred.reject("No controller has been specified.");
return deferred.promise;
}
// Get the actual html of the template.
getTemplate(options.template, options.templateUrl)
.then(function(template) {
// Create a new scope for the modal.
var modalScope = (options.scope || $rootScope).$new();
var rootScopeOnClose = $rootScope.$on('$locationChangeSuccess', cleanUpClose);
// Create the inputs object to the controller - this will include
// the scope, as well as all inputs provided.
// We will also create a deferred that is resolved with a provided
// close function. The controller can then call 'close(result)'.
// The controller can also provide a delay for closing - this is
// helpful if there are closing animations which must finish first.
var closeDeferred = $q.defer();
var closedDeferred = $q.defer();
var inputs = {
$scope: modalScope,
close: function(result, delay) {
if (delay === undefined || delay === null) delay = 0;
$timeout(function() {
cleanUpClose(result);
}, delay);
}
};
// If we have provided any inputs, pass them to the controller.
if (options.inputs) angular.extend(inputs, options.inputs);
// Compile then link the template element, building the actual element.
// Set the $element on the inputs so that it can be injected if required.
var linkFn = $compile(template);
var modalElement = linkFn(modalScope);
inputs.$element = modalElement;
// Create the controller, explicitly specifying the scope to use.
var controllerObjBefore = modalScope[options.controllerAs];
var modalController = $controller(options.controller, inputs, false, options.controllerAs);
if (options.controllerAs && controllerObjBefore) {
angular.extend(modalController, controllerObjBefore);
}
// Finally, append the modal to the dom.
if (options.appendElement) {
// append to custom append element
appendChild(options.appendElement, modalElement);
} else {
// append to body when no custom append element is specified
appendChild(body, modalElement);
}
// We now have a modal object...
var modal = {
controller: modalController,
scope: modalScope,
element: modalElement,
close: closeDeferred.promise,
closed: closedDeferred.promise
};
// ...which is passed to the caller via the promise.
deferred.resolve(modal);
function cleanUpClose(result) {
// Resolve the 'close' promise.
closeDeferred.resolve(result);
// Let angular remove the element and wait for animations to finish.
$animate.leave(modalElement)
.then(function () {
// Resolve the 'closed' promise.
closedDeferred.resolve(result);
// We can now clean up the scope
modalScope.$destroy();
// Unless we null out all of these objects we seem to suffer
// from memory leaks, if anyone can explain why then I'd
// be very interested to know.
inputs.close = null;
deferred = null;
closeDeferred = null;
modal = null;
inputs = null;
modalElement = null;
modalScope = null;
});
// remove event watcher
rootScopeOnClose && rootScopeOnClose();
}
})
.then(null, function(error) { // 'catch' doesn't work in IE8.
deferred.reject(error);
});
return deferred.promise;
};
}
return new ModalService();
}]);
I have spent hours on internet to figure out why this is happening but failed to solve it,i feel when any click event happens then it works fine but fails to close properly when on operation is performed.Please help!!
thanks in advance
I had the same issue and it was due to a comment at the top of my HTML file. When I removed the comment, it worked fine.
I didn't get the reason of this bug though.
hope you have the same case.

How to dismiss an angularjs alert when user changes route/state

I am using this angular js service/directive github pageto display alerts. An issue has been opened relating to the question I am asking but it has not been addressed by the developer.
i want first alert shown when user logs in to disappear when the user clicks logout but the alerts are stacking up on top of each other.
Here is a fiddle although I could not replicate the issue but it shows the structure of my code. fiddle
html:
<body ng-app="app">
<mc-messages></mc-messages>
<button ng-click="login()">Login</button>
<button ng-click="logout()">Logout</button>
</body>
js:
/*jshint strict:false */
'use strict';
var app = angular.module('app', ['MessageCenterModule']);
app.controller(function ($scope, messageCenterService, $location) {
$scope.login = function () {
$location.path('/');
messageCenterService.add('success',
'You are now loggedin!', {
status: messageCenterService.status.next
});
};
$scope.logout = function () {
$location.path('login');
messageCenterService.add('success',
'You are now loggedout!', {
status: messageCenterService.status.next
}
};
});
// Create a new angular module.
var MessageCenterModule = angular.module('MessageCenterModule', []);
// Define a service to inject.
MessageCenterModule.
service('messageCenterService', ['$rootScope', '$sce', '$timeout',
function ($rootScope, $sce, $timeout) {
return {
mcMessages: this.mcMessages || [],
status: {
unseen: 'unseen',
shown: 'shown',
/** #var Odds are that you will show a message and right after that
* change your route/state. If that happens your message will only be
* seen for a fraction of a second. To avoid that use the "next"
* status, that will make the message available to the next page */
next: 'next',
/** #var Do not delete this message automatically. */
permanent: 'permanent'
},
add: function (type, message, options) {
var availableTypes = ['info', 'warning', 'danger', 'success'],
service = this;
options = options || {};
if (availableTypes.indexOf(type) === -1) {
throw "Invalid message type";
}
var messageObject = {
type: type,
status: options.status || this.status.unseen,
processed: false,
close: function () {
return service.remove(this);
}
};
messageObject.message = options.html ? $sce.trustAsHtml(message) : message;
messageObject.html = !! options.html;
if (angular.isDefined(options.timeout)) {
messageObject.timer = $timeout(function () {
messageObject.close();
}, options.timeout);
}
this.mcMessages.push(messageObject);
return messageObject;
},
remove: function (message) {
var index = this.mcMessages.indexOf(message);
this.mcMessages.splice(index, 1);
},
reset: function () {
this.mcMessages = [];
},
removeShown: function () {
for (var index = this.mcMessages.length - 1; index >= 0; index--) {
if (this.mcMessages[index].status == this.status.shown) {
this.remove(this.mcMessages[index]);
}
}
},
markShown: function () {
for (var index = this.mcMessages.length - 1; index >= 0; index--) {
if (!this.mcMessages[index].processed) {
if (this.mcMessages[index].status == this.status.unseen) {
this.mcMessages[index].status = this.status.shown;
} else if (this.mcMessages[index].status == this.status.next) {
this.mcMessages[index].status = this.status.unseen;
}
this.mcMessages[index].processed = true;
}
}
},
flush: function () {
$rootScope.mcMessages = this.mcMessages;
}
};
}]);
MessageCenterModule.
directive('mcMessages', ['$rootScope', 'messageCenterService', function ($rootScope, messageCenterService) {
/*jshint multistr: true */
var templateString = '\
<div id="mc-messages-wrapper">\
<div class="alert alert-{{ message.type }} {{ animation }}" ng-repeat="message in mcMessages">\
<a class="close" ng-click="message.close();" data-dismiss="alert" aria-hidden="true">×</a>\
<span ng-switch on="message.html">\
<span ng-switch-when="true">\
<span ng-bind-html="message.message"></span>\
</span>\
<span ng-switch-default>\
{{ message.message }}\
</span>\
</div>\
</div>\
';
return {
restrict: 'EA',
template: templateString,
link: function (scope, element, attrs) {
// Bind the messages from the service to the root scope.
messageCenterService.flush();
var changeReaction = function (event, to, from) {
// Update 'unseen' messages to be marked as 'shown'.
messageCenterService.markShown();
// Remove the messages that have been shown.
messageCenterService.removeShown();
$rootScope.mcMessages = messageCenterService.mcMessages;
messageCenterService.flush();
};
$rootScope.$on('$locationChangeStart', changeReaction);
scope.animation = attrs.animation || 'fade in';
}
};
}]);
Hope this is clear enough for someone to help me. If not let me know and I can try to clarify.

Using ui-router with Bootstrap-ui modal

I know this has been covered many times and most articles refer to this bit of code: Modal window with custom URL in AngularJS
But I just don't get it. I don't find that to be very clear at all. I also found this jsfiddle which was actually great, very helpful except this doesn't add the url and allow for me to use the back button to close the modal.
Edit: This is what I need help with.
So let me try explain what I am trying to achieve. I have a form to add a new item, and I have a link 'add new item'. I would like when I click 'add new item' a modal pops up with the form I have created 'add-item.html'. This is a new state so the url changes to /add-item.
I can fill out the form and then choose to save or close. Close, closes the modal :p (how odd) . But I can also click back to close the modal as well and return to the previous page(state).
I don't need help with Close at this point as I am still struggling with actually getting the modal working.
This is my code as it stands:
Navigation Controller: (is this even the correct place to put the modal functions?)
angular.module('cbuiRouterApp')
.controller('NavbarCtrl', function ($scope, $location, Auth, $modal) {
$scope.menu = [{
'title': 'Home',
'link': '/'
}];
$scope.open = function(){
// open modal whithout changing url
$modal.open({
templateUrl: 'components/new-item/new-item.html'
});
// I need to open popup via $state.go or something like this
$scope.close = function(result){
$modal.close(result);
};
};
$scope.isCollapsed = true;
$scope.isLoggedIn = Auth.isLoggedIn;
$scope.isAdmin = Auth.isAdmin;
$scope.getCurrentUser = Auth.getCurrentUser;
$scope.logout = function() {
Auth.logout();
$location.path('/login');
};
$scope.isActive = function(route) {
return route === $location.path();
};
});
This is how I am activating the modal:
<li ng-show='isLoggedIn()' ng-class='{active: isActive("/new-item")}'>
<a href='javascript: void 0;' ng-click='open()'>New Item</a>
</li>
new-item.html:
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items"><a ng-click="selected.item = item">{{ item }}</a></li>
</ul>Selected:<b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button ng-click="ok()" class="btn btn-primary">OK</button>
<button ng-click="close()" class="btn btn-primary">OK</button>
</div>
Also whilst this does open a modal it doesn't close it as I couldn't work that out.
It's intuitive to think of a modal as the view component of a state. Take a state definition with a view template, a controller and maybe some resolves. Each of those features also applies to the definition of a modal. Go a step further and link state entry to opening the modal and state exit to closing the modal, and if you can encapsulate all of the plumbing then you have a mechanism that can be used just like a state with ui-sref or $state.go for entry and the back button or more modal-specific triggers for exit.
I've studied this fairly extensively, and my approach was to create a modal state provider that could be used analogously to $stateProvider when configuring a module to define states that were bound to modals. At the time, I was specifically interested in unifying control over modal dismissal through state and modal events which gets more complicated than what you're asking for, so here is a simplified example.
The key is making the modal the responsibility of the state and using hooks that modal provides to keep the state in sync with independent interactions that modal supports through the scope or its UI.
.provider('modalState', function($stateProvider) {
var provider = this;
this.$get = function() {
return provider;
}
this.state = function(stateName, options) {
var modalInstance;
$stateProvider.state(stateName, {
url: options.url,
onEnter: function($modal, $state) {
modalInstance = $modal.open(options);
modalInstance.result['finally'](function() {
modalInstance = null;
if ($state.$current.name === stateName) {
$state.go('^');
}
});
},
onExit: function() {
if (modalInstance) {
modalInstance.close();
}
}
});
};
})
State entry launches the modal. State exit closes it. The modal might close on its own (ex: via backdrop click), so you have to observe that and update the state.
The benefit of this approach is that your app continues to interact mainly with states and state-related concepts. If you later decide to turn the modal into a conventional view or vice-versa, then very little code needs to change.
Here is a provider that improves #nathan-williams solution by passing resolve section down to the controller:
.provider('modalState', ['$stateProvider', function($stateProvider) {
var provider = this;
this.$get = function() {
return provider;
}
this.state = function(stateName, options) {
var modalInstance;
options.onEnter = onEnter;
options.onExit = onExit;
if (!options.resolve) options.resolve = [];
var resolveKeys = angular.isArray(options.resolve) ? options.resolve : Object.keys(options.resolve);
$stateProvider.state(stateName, omit(options, ['template', 'templateUrl', 'controller', 'controllerAs']));
onEnter.$inject = ['$uibModal', '$state', '$timeout'].concat(resolveKeys);
function onEnter($modal, $state, $timeout) {
options.resolve = {};
for (var i = onEnter.$inject.length - resolveKeys.length; i < onEnter.$inject.length; i++) {
(function(key, val) {
options.resolve[key] = function() { return val }
})(onEnter.$inject[i], arguments[i]);
}
$timeout(function() { // to let populate $stateParams
modalInstance = $modal.open(options);
modalInstance.result.finally(function() {
$timeout(function() { // to let populate $state.$current
if ($state.$current.name === stateName)
$state.go(options.parent || '^');
});
});
});
}
function onExit() {
if (modalInstance)
modalInstance.close();
}
return provider;
}
}]);
function omit(object, forbidenKeys) {
var prunedObject = {};
for (var key in object)
if (forbidenKeys.indexOf(key) === -1)
prunedObject[key] = object[key];
return prunedObject;
}
then use it like that:
.config(['modalStateProvider', function(modalStateProvider) {
modalStateProvider
.state('...', {
url: '...',
templateUrl: '...',
controller: '...',
resolve: {
...
}
})
}]);
I answered a similar question, and provided an example here:
Modal window with custom URL in AngularJS
Has a complete working HTML and a link to plunker.
The $modal itself doesn't have a close() funcftion , I mean If you console.log($modal) , You can see that there is just an open() function.
Closing the modal relies on $modalInstance object , that you can use in your modalController.
So This : $modal.close(result) is not actually a function!
Notice :
console.log($modal);
==>> result :
Object { open: a.$get</k.open() }
// see ? just open ! , no close !
There is some way to solve this , one way is :
First you must define a controller in your modal like this :
$modal.open({
templateUrl: 'components/new-item/new-item.html',
controller:"MyModalController"
});
And then , Later on , :
app.controller('MyModalController',function($scope,$modalInstance){
$scope.closeMyModal = function(){
$modalInstance.close(result);
}
// Notice that, This $scope is a seperate scope from your NavbarCtrl,
// If you want to have that scope here you must resolve it
});

Resources