Issue
Angular.js modal and controller scope issue
My current Angular 1.x application work as follows - I have tempplate, let's call it 'view' which calls a function on ng-click, the button example:
<div ng-controller="viewController as listing">
<button ng-click="listing.openModal()" ng-disabled="listing.isButtonDisabled">
</div>
$scope.isButtonDisabled = false;
$scope.openModal = ModalService();
The controller for the view uses a factory which opens the modal, I use a factory since severalcontrollers use the same modal functionality. As can be seen from above I do not disable the button initisally.
The modal pops open and it has it's own controller that is concerned with the input received from the user in the modal. When the input has been processed, if successful I want to disable the button on the original view which opens the modal.
The problem as i see it is that I am out of scope in my new controller - if I do this:
$scope.isButtonDisabled = true;
It will apply to the scope of the modal, not the original view which calls for the modal to open?
UPDATE
I am using this angular modal service:
I created this Plunker to demonstrate my code:
Solution
From the DOCs:
Calling
showModal
returns a promise which is resolved when the modal DOM element is created and the controller for it is created. The promise returns amodal
object which contains the element created, the controller, the scope and two promises:close
andclosed
. Both are resolved to the result of the modalclose
function, butclose
is resolved as soon as the modalclose
function is called, whileclosed
is only resolved once the modal has finished animating and has been completely removed from the DOM.
The service should return the promise:
app.service('FooBar', function FooBar(ModalService) {
this.openModal = function(template, controller) {
// Note: in order to fire the modal pop-up the id of the script tag
//of the modal should match the first param of ng-click on the button
// eg. <script type="text/ng-template" id="messageSeller">
// should match: ng-click="openModal('messageSeller',
// 'messagesAddController')"
//IMPORTANT return promise
̶M̶o̶d̶a̶l̶S̶e̶r̶v̶i̶c̶e̶.̶s̶h̶o̶w̶M̶o̶d̶a̶l̶(̶{̶
return ModalService.showModal({
templateUrl: template, // <- ensure the value of template
// matches the id of one of the modal divs
controller: controller,
inputs: {}
})
};
})
Use the returned promise in the controller:
app.controller('Controller', function(FooBar) {
var listing = this;
listing.isButtonDisabled = false;
listing.openModal = function(template, controller){
FooBar(template, controller)
.then(function(model) {
return modal.close;
}).then(function(value) {
console.log(value);
listing.isButtonDisabled = true;
}).catch(function(reason) {
console.log("Modal error:", reason);
});
}
});
Disable the button when the modal successfully returns a value.
Answered By - georgeawg
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.