AngularJS call AngularStrap Modal from service - angularjs

I am trying to create a service to display Angular-Strap modals since I have many different parts of code that will need to trigger a modal and I don't want to run into a situation where I would have a circular reference.
This is code that works where you have access to $scope. For instance, in the applications controller.
function MyModalController($scope) {
$scope.title = 'Draw Object Properties';
$scope.content = 'Hello Modal<br />This is place holder test';
};
MyModalController.$inject = ['$scope'];
// Pre-fetch an external template populated with a custom scope
var myOtherModal = $modal({ controller: MyModalController, templateUrl: 'webmapapi/modal/toolproperties.html', show: false });
// Show when some event occurs (use $promise property to ensure the template has been loaded)
$scope.showModal = function () {
myOtherModal.$promise.then(myOtherModal.show);
};
Like I said I need to call this from a service though.
(function (angular, undefined) {
'use strict';
angular.module('ModalService', ['service', 'webValues', 'msObjects', 'mgcrea.ngStrap',])
.config(function ($modalProvider) {
angular.extend($modalProvider.defaults, {
html: true
});
})
.factory("ModalService", function (MapApiService, webValues, VectorObjs,$modal) {
var modalSVC = {
};
modalSVC.showModal = function (modalType) {
var scope = angular.element(document.getElementById('mainContainer')).scope();
function MyModalController(scope) {
scope.title = 'Draw Object Properties';
scope.content = 'Hello Modal<br />This is place holder test';
};
MyModalController.$inject = ['scope'];
// Pre-fetch an external template populated with a custom scope
var myOtherModal = $modal({ controller: MyModalController, templateUrl: 'myURL.html', show: true });
// Show when some event occurs (use $promise property to ensure the template has been loaded)
myOtherModal.show;
};
return modalSVC;
})
}(angular));
The above does not like the scope I'm getting.

Okay, It's amazing how easy something can be once you know what you are doing!!
Essentially you will want to set up a service...
(function (angular, undefined) {
'use strict';
angular.module('ModalService', ['mgcrea.ngStrap'])
.controller('ModalServiceController', modalServiceController)
.factory("ModalService", function ($animate, $document, $compile, $controller, $http, $rootScope, $q, $templateRequest, $timeout, $modal) {
function ModalService() {
var self = this;
self.showModal = function (title,templateUrl) {
var modal = $modal({
title: title,
templateUrl: templateUrl,
show: true,
backdrop: 'static',
controller: 'ModalServiceController'
});
modal.show;
};
}
return new ModalService();
})
modalServiceController.$inject = ['$scope', '$modal'];
function modalServiceController($scope,$modal) {
//title and content need to be populated so I just left the default values
$scope.title = 'Draw Object Properties';
$scope.content = 'Hello Modal<br />This is place holder test';
};
}(angular));
Now that you have your controller set up and injecting $modal, all you have to do from anywhere you have your service reference injected is...
ModalService.showModal("Your Title",
"Your URL");
I have a template(must be formatted as ) set up as Template.html and the contents are...
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" ng-show="title">
<button type="button" class="close" ng-click="$hide()">×</button>
<h4 class="modal-title" ng-bind-html="title"></h4>
</div>
<div class="modal-body" ng-show="content">
<h4>Text in a modal</h4>
<p ng-bind-html="content"></p>
<pre>2 + 3 = {{ 2 + 3 }}</pre>
<h4>Popover in a modal</h4>
<p>This <a href="#" role="button" class="btn btn-default popover-test" data-title="A Title" data-content="And here's some amazing content. It's very engaging. right?" bs-popover>button</a> should trigger a popover on click.</p>
<h4>Tooltips in a modal</h4>
<p><a href="#" class="tooltip-test" data-title="Tooltip" bs-tooltip>This link</a> and <a href="#" class="tooltip-test" data-title="Tooltip" bs-tooltip>that link</a> should have tooltips on hover.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="$hide()">Close</button>
<button type="button" class="btn btn-primary" ng-click="$hide()">Save changes</button>
</div>
</div>
</div>
I hope this helps you!!

Related

Reuse a view as a modal and non-modal (angularjs + bootstrap-ui)

I currently use views/foo.html as a normal view.
Say this view has this:
<p>Hello</p>
Now I want to reuse views/foo.html as the content of a modal, but I'd like to wrap it with this:
<div class="modal-header">
<h3 class="modal-title">Foo</h3>
</div>
<div class="modal-body">
<!-- I want to include views/foo.html in here -->
</div>
So the modal would look like this:
<div class="modal-header">
<h3 class="modal-title">Foo</h3>
</div>
<div class="modal-body">
<p>Hello</p>
</div>
The modal invoker is the following: (notice the comment)
$scope.openFooModal = function () {
var modalScope = $scope.$new();
var modalInstance = $uibModal.open({
templateUrl: 'views/foo.html', /* HERE I NEED TO WRAP IT */
controller: 'fooController',
scope: modalScope,
size: 'lg'
});
modalInstance.result.then(function (result) {
}, null);
};
What is the best solution?
Should I create a foo2.html ?
So at the end the comment made by JB Nizet worked as a start, but there was this issue:
Inject $uibModalInstance to a controllar not initiated by a $uibModal
This is what I did finally:
view in charge of opening the modal or displaying it as an ng-view:
<body ng-controller="indexController">
<ul>
<li>
Open as modal
</li>
<li>
Open as non modal
</li>
</ul>
<div ng-view=""></div> <!-- Used by routeProvider -->
</body>
...its controller
angular.module('myApp').controller('indexController', ['$scope','$uibModal', function($scope,$uibModal) {
$scope.openModal = function () {
var modalScope = $scope.$new();
var modalInstance = $uibModal.open({
templateUrl: 'foo-as-modal.html',
controller: 'fooController',
scope: modalScope
});
modalScope.modalInstance = modalInstance;
// ^ I'm giving the modal his own reference
// using the scope. Injecting wont work on
// the non-modal case!
modalInstance.result.then(function (result) {
}, null);
};
}]);
view to be reused as a modal or as a non-modal:
<p>Hello {{name}}</p>
its controller:
angular.module('myApp').controller('fooController', ['$scope', function($scope) {
// ^
// I'm not injecting
// uibModalInstance
// (this is important)
$scope.name = "John";
$scope.cancel = function () {
$scope.modalInstance.dismiss('cancel');
// ^ I can access the modalInstance by the $scope
};
}]);
view to be used as a modal (wrapper)
<div class="modal-header">
<h3 class="modal-title">I'm a modal</h3>
</div>
<div class="modal-body">
<ng-include src="'foo.html'"></ng-include> <!-- Credits to JB's comment -->
</div>
<div class="modal-footer">
<button class="btn btn-default" ng-click="cancel()">Close</button>
</div>
routeProvider
$routeProvider
.when('/nonmodal', {
templateUrl: 'foo.html',
controller: 'fooController'
})
Here is a plunkr: https://plnkr.co/edit/ZasHQhl6M5cCc9yaZTd5?p=info

Unable to make angular-formly work within a ng-template of an angular-ui-bootstrap modal

I am using angular-formly to build a form inside an angular-ui-bootstrap modal, the following code works when the form is placed outside the modal template but it doesn't when placed inside the ng-template, it just doesn't print the fields at all.
I believe this should work but I don't know how the life-cycle of angular-formly runs, so I am unable to identify how to make the fields show up inside my bootstrap modal template.
The issue is clearly related to the ng-template, it appears not to render the form even if the fields array is passed correctly.
var app = angular.module("demo", ['dndLists', 'ui.bootstrap', 'formly', 'formlyBootstrap']);
app.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, items, User) {
var vm = this;
vm.loadingData = User.getUserData().then(function(result) {
vm.model = result[0];
vm.fields = result[1];
vm.originalFields = angular.copy(vm.fields);
console.log(vm);
});
});
app.controller("AdvancedDemoController", function($scope, $uibModal){
$scope.modalOpen = function(event, index, item){
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: 'md',
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
In my view:
<!-- Template for a modal -->
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<div ng-if="vm.loadingData.$$state.status === 0" style="margin:20px 0;font-size:2em">
<strong>Loading...</strong>
</div>
<div ng-if="vm.loadingData.$$status.state !== 0">
<form ng-submit="vm.onSubmit()" novalidate>
<formly-form model="vm.model" fields="vm.fields" form="vm.form">
<button type="submit" class="btn btn-primary submit-button">Submit</button>
</formly-form>
</form>
</div>
<ul>
<li ng-repeat="item in items">
{{ item }}
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
</script>
Any ideas?
When calling $uibModal.open you need to specify controllerAs: 'vm' (that's what you're template assumes the controller is defined as).

Angular modal- the modal is displayed from the start and I can't hide it

I am new to angular js
I have to open a modal dialog which display some selected value.
Open Modal
<div modal="showModal" close="cancel()">
<div class="modal-header">
<h4>Modal Dialog</h4>
</div>
<div class="modal-body">
<p>E{{inputValue}}</p>
</div>
<div class="modal-footer">
<button class="btn btn-success" ng-click="ok()">Okay</button>
<button class="btn" ng-click="cancel()">Cancel</button>
</div>
</div>
The controller for the module which contain the modal is:
var app = angular.module('myApp', ['ui.bootstrap.modal']);
app.controller('ctrlTags', function($scope){
$scope.inputValue=$('input:checked').val()
$scope.open = function() {
$scope.showModal = true;
return $scope.inputValue;
};
$scope.ok = function() {
$scope.showModal = false;
};
$scope.cancel = function() {
$scope.showModal = false;
};
});
For some reason the modal is displayed as is it is a regular part of the page (doesn't function as a modal)
Toggling a boolean is not how ui-boostrap modals are opened. See documentation. Basically you have to call $uibModal.open with a template:
$scope.open = function() {
var modalInstance = $uibModal.open({
templateUrl: 'myModal.html',
controller: 'ModalInstanceCtrl'
});
}
Have a look at this plunker where I'm passing a value to the modal, through the resolve property of $uibModal.open.

Angular bootstrap ui modal scope binding with parent

I am having an Angular issue getting a modal scope to unbind from the parent scope. I want the scope object I pass into the modal to be separate from the corresponding scope object.
No matter how I structure the modal object the parent always mirrors it. The only solution I have found is to change the object property names, but that would be cumbersome to do for every modal in my project.
For example, I can have a $scope variable in the parent $scope.parentData.firstName and a modal variable $scope.modalData.a.b.c.firstName, and the parent will mirror the modal value.
I guess there is some parent child $scope issues here that I am not getting.
Here is a plunk illustrating the issue:
http://plnkr.co/edit/5naWXfkv7kmzFp7U2KPv?p=preview
HTML:
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<div class="modal-body">
<input ng-model="modalData.a" />
<input ng-model="modalData.b" />
<input ng-model="modalData.c" />
Selected: <b>{{ sourceData }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
<button class="btn btn-default" ng-click="open()">Open me!</button>
{{sourceData}}
<div ng-show="sourceData">Selection from a modal: {{ test }}</div>
</div>
</body>
</html>
JS:
angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log) {
$scope.sourceData = {a:'abc',b:'bcd',c:'cde'};
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
resolve: {
data: function () {
return $scope.sourceData;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.scopeData = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
};
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
var ModalInstanceCtrl = function ($scope, $modalInstance, data) {
$scope.modalData = {};
$scope.modalData = data;
$scope.ok = function () {
$modalInstance.close($scope.modalData);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
You are passing a reference to your current object, what you want to do is use angular.copy() to pass a deep copy of the object to the modal plnkr:
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
resolve: {
data: function () {
return angular.copy($scope.sourceData); // deep copy
}
}
});

Disable button in angular js

I have 2 buttons in my page "Save Set" & "Load Set".
"Save Set" button has ng-disabled=isSaveDisabled()
.....
.controller('saveLoadSetToolbarBtn', ['$scope','$modal','propertiesModified',
function ($scope,$modal,propertiesModified) {
$scope.loadTuneSet = function () {
$modal.open({
templateUrl: 'loadSetDlg.html',
controller: 'loadSetCtrl'
});
};
$scope.isSaveDisabled = function() {
return !propertiesModified.get();
};
.......
When I click Load Set, it will open a popup and their I'll have OK button. On this click, I should disable the "Save Set" button
OK Button,
.controller('loadSetCtrl', ['$scope', '$modalInstance', 'generalDataService',
function ($scope, $modalInstance, generalDataService) {
$scope.items = [];
$scope.selectedSet = undefined;
$scope.ok = function () {
//doing some logic
closeDialog();
$modalInstance.close();
};
If any value changes happen in my page then this "Save Set" button will be enabled. problem is if I change any value in my page this button is enabling (as expected). If I click "Load Set" button, popup will open and on OK button click (available on Popup) then this "Save Set" should go back to Disable state. I should be able to return boolean value true through this isSaveDisabled function on OK button click.
Simple:
<button ng-model="btnSaveSet" ng-disabled="btnSaveSet_disabled"
ng-click="btnSaveSet_disabled=true">SaveSet</button>
I think you're trying to code a Modal View, like the Demo of this page : http://angular-ui.github.io/bootstrap/ .
I recommend to try this demo and modify it to fit your needs, because there is not much to change. I try to give you some hints in the comments of the code:
This is the JavaScript Code:
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {
$scope.items = ['tuneSet', 'tuneSet2','tuneSet3'];
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'loadSetDlg.html', // name it like the Template for the Modal
controller: 'loadSetCtrl', // name it like the used controller for the Modal
size: size, // not necessary for you
resolve: {
items: function () { // this will pass in your items into the ModalCtrl
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) { // here is the callback, when the
$scope.selected = selectedItem; // Modal get closed
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
// Here you can implement your logic depending on the user-input that is available on $scope.selected
// it is an object.
console.log($scope.selected); // here you can see it in the console.
});
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
angular.module('ui.bootstrap.demo').controller('loadSetCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0] // this will catch the user input (click on link)
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item); // this will pass the chosen tuneSet back to
}; // ModalDemoCtrl
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
And this is the HTML you need:
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="loadSetDlg.html">
<div class="modal-header">
<h3 class="modal-title">TuneSet selection!</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 class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
<button class="btn btn-default" ng-click="open()">Open me!</button>
<button class="btn btn-default" ng-click="open('lg')">Large modal</button>
<button class="btn btn-default" ng-click="open('sm')">Small modal</button>
<div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>

Resources