AngularJS reusable modal bootstrap directive - angularjs

I'm new with AngularJS. I'm trying to implement a reusable modal Bootstrap.
This is the index.html:
<div ng-controller="mymodalcontroller">
<modal lolo="modal1" modal-body='body' modal-footer='footer' modal-header='header' data-ng-click="myRightButton()"></modal>
Launch Demo Modal
</div>
This is the module, controller and directive:
var myModal = angular.module('myModal', []);
myModal.controller('mymodalcontroller', function ($scope) {
$scope.header = 'Put here your header';
$scope.body = 'Put here your body';
$scope.footer = 'Put here your footer';
$scope.myRightButton = function (bool) {
alert('!!! first function call!');
};
});
myModal.directive('modal', function () {
return {
restrict: 'EA',
scope: {
title: '=modalTitle',
header: '=modalHeader',
body: '=modalBody',
footer: '=modalFooter',
callbackbuttonleft: '&ngClickLeftButton',
callbackbuttonright: '&ngClick',
handler: '=lolo'
},
templateUrl: 'partialmodal.html',
transclude: true,
controller: function ($scope) {
$scope.handler = 'pop';
},
};
});
And this is the html template:
<div id="{{handler}}" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">{{header}}</h4>
</div>
<div class="modal-body">
<p class="text-warning">{{body}}</p>
</div>
<div class="modal-footer">
<p class="text-left">{{footer}}</p>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-ng-click="callbackbuttonright(), $event.stopPropagation()">Save changes</button>
</div>
</div>
</div>
</div>
I want the 'Launch Alert' button (in the modal) executes the alert and it does it well. The problem is that it is launched when clicking the 'Cancel' button in the Modal and when the window closes. Any ideas?
Here is the working code:CodeThank you.

I would suggest you not bind to ng-click. It does some other magic stuff that can screw with things. There is also a syntax error in your partial.
I've fixed those issues in my fork here:
http://plnkr.co/edit/2jK2GFcKSiKgMQMynD1R?p=preview
To summarize:
script.js:
Change your callbackbuttonright binding from ngClick to ngClickRightButton
myModal.directive('modal', function () {
return {
restrict: 'EA',
scope: {
title: '=modalTitle',
header: '=modalHeader',
body: '=modalBody',
footer: '=modalFooter',
callbackbuttonleft: '&ngClickLeftButton',
callbackbuttonright: '&ngClickRightButton',
handler: '=lolo'
},
templateUrl: 'partialmodal.html',
transclude: true,
controller: function ($scope) {
$scope.handler = 'pop';
},
};
});
index.html:
Change data-ng-click to data-ng-click-right-button
<modal lolo="modal1" modal-body="body" modal-footer="footer" modal-header="header" data-ng-click-right-button="myRightButton()"></modal>
Another minor issue:
partialmodal.html:
Change , to ;
<button type="button" class="btn btn-primary" data-ng-click="callbackbuttonright(); $event.stopPropagation()">Launch Alert</button>

If anyone is still interested, here is a example I recently worked on with bootstrap modal and angularjs directive.
HTML:
<modal visible="showModal1" on-sown="modalOneShown()" on-hide="modalOneHide()">
<modal-header title="Modal Titel 1"></modal-header>
<modal-body>
<h3>This is modal body</h3>
</modal-body>
<modal-footer>
<button class="btn btn-primary" ng-click="hide(1)">Save</button>
</modal-footer>
</modal>
JavaScript:
var myModalApp = angular.module('myModalApp',[]);
myModalApp.directive('modal', function(){
return {
template: '<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm"><div class="modal-content" ng-transclude><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button><h4 class="modal-title" id="myModalLabel">Modal title</h4></div></div></div></div>',
restrict: 'E',
transclude: true,
replace:true,
scope:{visible:'=', onSown:'&', onHide:'&'},
link:function postLink(scope, element, attrs){
$(element).modal({
show: false,
keyboard: attrs.keyboard,
backdrop: attrs.backdrop
});
scope.$watch(function(){return scope.visible;}, function(value){
if(value == true){
$(element).modal('show');
}else{
$(element).modal('hide');
}
});
$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.onSown({});
});
});
$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.onHide({});
});
});
}
};
}
);
myModalApp.directive('modalHeader', function(){
return {
template:'<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button><h4 class="modal-title">{{title}}</h4></div>',
replace:true,
restrict: 'E',
scope: {title:'#'}
};
});
myModalApp.directive('modalBody', function(){
return {
template:'<div class="modal-body" ng-transclude></div>',
replace:true,
restrict: 'E',
transclude: true
};
});
myModalApp.directive('modalFooter', function(){
return {
template:'<div class="modal-footer" ng-transclude></div>',
replace:true,
restrict: 'E',
transclude: true
};
});
function ModalController($scope){
$scope.title = "Angularjs Bootstrap Modal Directive Example";
$scope.showModal1 = false;
$scope.showModal2 = false;
$scope.hide = function(m){
if(m === 1){
$scope.showModal1 = false;
}else{
$scope.showModal2 = false;
}
}
$scope.modalOneShown = function(){
console.log('model one shown');
}
$scope.modalOneHide = function(){
console.log('model one hidden');
}
}

Compared to other options, below given the minimalist approach using Angular Bootstrap and an angular factory. See a sample snippet below.
Reusable modal view - ConfirmationBox.html
<div class="modal-header">
<h3 class="modal-title">{{title}}</h3>
</div>
<div class="modal-body">
{{message}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-warn" data-ng-click="ok(); $event.stopPropagation()">OK</button>
<button type="button" class="btn btn-default" data-ng-click="cancel(); $event.stopPropagation()">Cancel</button>
</div>
Reusable module and shared factory, for handling the reusable modal dialog
angular.module('sharedmodule',['ui.bootstrap', 'ui.bootstrap.tpls'])
.factory("sharedService",["$q", "$modal", function ($q, $modal)
{
var _showConfirmDialog = function (title, message)
{
var defer = $q.defer();
var modalInstance = $modal.open({
animation: true,
size: "sm",
templateUrl: 'ConfirmationBox.html',
controller: function ($scope, $modalInstance)
{
$scope.title = title;
$scope.message = message;
$scope.ok = function ()
{
modalInstance.close();
defer.resolve();
};
$scope.cancel = function ()
{
$modalInstance.dismiss();
defer.reject();
};
}
});
return defer.promise;
}
return {
showConfirmDialog: _showConfirmDialog
};
}]);
Portion of your View, using the shared modal dialog
<a data-ng-click="showConfirm()">Go Back to previous page</a>
Controller of your view, opening your shared reusable modal dialog and handling notifications (Ok and Cancel)
var myModule = angular.module("mymodule", ['sharedmodule', 'ui.bootstrap', 'ui.bootstrap.tpls']);
myModule.controller('myController', ["$scope", "sharedService", "$window",
function ($scope, sharedService, $window)
{
$scope.showConfirm = function ()
{
sharedService.showConfirmDialog(
'Confirm!',
'Any unsaved edit will be discarded. Are you sure to navigate back?')
.then(function ()
{
$window.location = '#/';
},
function ()
{
});
};
}]);

Related

Angular Boostrap Modal Service

I am attempting to open a modal, when clicking the edit button on an Angular UI Grid. I am new to Angular and still learning. I have done some searching but still cannot work out how to inject my modal instance into the StaffController, so it can be used. Will really appreciate any advice / help on this. Thanks,
I am using the angular modal example off: https://angular-ui.github.io/bootstrap/
Index File(Contains the Grid and example Modal Buttons):
#*Staff Grid*#
<body ng-app="Application">
<div ng-controller="ApiStaffController">
<div class="table-responsive angular-grid" ui-grid="gridOptions" ui-
grid-move-columns ui-grid-resize-columns ui-grid-exporter ui-grid-selection>
</div>
</div>
<div ng-controller="ModalDemoCtrl as $ctrl" class="modal-demo">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title" id="modal-title">Create User</h3>
</div>
<div class="modal-body" id="modal-body">
<label asp-for="Person.Forename" class="control-label"></label>
<input type="text" class="form-control" ng-model="$ctrl.newUser.Forename" />
<label asp-for="Person.Surname" class="control-label"></label>
<input type="text" class="form-control" ng-model="$ctrl.newUser.Surname" />
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="$ctrl.ok()" ng-disabled="!$ctrl.newUser.Forename || !$ctrl.newUser.Surname">OK</button>
<button class="btn btn-warning" type="button" ng-click="$ctrl.cancel()">Cancel</button>
</div>
</script>
<script type="text/ng-template" id="stackedModal.html">
<div class="modal-header">
<h3 class="modal-title" id="modal-title-{{name}}">The {{name}} modal!</h3>
</div>
<div class="modal-body" id="modal-body-{{name}}">
Having multiple modals open at once is probably bad UX but it's technically possible.
</div>
</script>
<button type="button" class="btn btn-default" ng-click="$ctrl.open()">Open me!</button>
<button type="button" class="btn btn-default" ng-click="$ctrl.open('lg')">Large modal</button>
<button type="button" class="btn btn-default" ng-click="$ctrl.open('sm')">Small modal</button>
<button type="button" class="btn btn-default" ng-click="$ctrl.open('sm', '.modal-parent')">
Modal appended to a custom parent
</button>
<button type="button" class="btn btn-default" ng-click="$ctrl.toggleAnimation()">Toggle Animation ({{ $ctrl.animationsEnabled }})</button>
<button type="button" class="btn btn-default" ng-click="$ctrl.openComponentModal()">Open a component modal!</button>
<button type="button" class="btn btn-default" ng-click="$ctrl.openMultipleModals()">
Open multiple modals at once
</button>
<div ng-show="$ctrl.selected">Selection from a modal: {{ $ctrl.selected }}</div>
<div class="modal-parent">
</div>
</div>
I have a file named: ModalController that contains the below: (This is from the example)
angular.module('Application').controller('ModalDemoCtrl', function
($uibModal, $log, $document) {
var $ctrl = this;
$ctrl.items = ['item1', 'item2', 'item3'];
$ctrl.animationsEnabled = true;
$ctrl.open = function (size, parentSelector) {
var parentElem = parentSelector ?
angular.element($document[0].querySelector('.modal-demo ' +
parentSelector)) : undefined;
var modalInstance = $uibModal.open({
animation: $ctrl.animationsEnabled,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
controllerAs: '$ctrl',
size: size,
appendTo: parentElem,
resolve: {
items: function () {
return $ctrl.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$ctrl.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$ctrl.openComponentModal = function () {
var modalInstance = $uibModal.open({
animation: $ctrl.animationsEnabled,
component: 'modalComponent',
resolve: {
items: function () {
return $ctrl.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$ctrl.selected = selectedItem;
}, function () {
$log.info('modal-component dismissed at: ' + new Date());
});
};
$ctrl.openMultipleModals = function () {
$uibModal.open({
animation: $ctrl.animationsEnabled,
ariaLabelledBy: 'modal-title-bottom',
ariaDescribedBy: 'modal-body-bottom',
templateUrl: 'stackedModal.html',
size: 'sm',
controller: function ($scope) {
$scope.name = 'bottom';
}
});
$uibModal.open({
animation: $ctrl.animationsEnabled,
ariaLabelledBy: 'modal-title-top',
ariaDescribedBy: 'modal-body-top',
templateUrl: 'stackedModal.html',
size: 'sm',
controller: function ($scope) {
$scope.name = 'top';
}
});
};
$ctrl.toggleAnimation = function () {
$ctrl.animationsEnabled = !$ctrl.animationsEnabled;
};
});
// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.
angular.module('Application').controller('ModalInstanceCtrl', function
($uibModalInstance, StaffService, items) {
var $ctrl = this;
$ctrl.items = items;
$ctrl.selected = {
item: $ctrl.items[0]
};
$ctrl.ok = function () {
alert($ctrl.newUser.Forename);
alert($ctrl.newUser.Surname);
//$uibModalInstance.close($ctrl.selected.item); //Untill we do the saving staff
};
$ctrl.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});
// Please note that the close and dismiss bindings are from $uibModalInstance.
angular.module('Application').component('modalComponent', {
templateUrl: 'myModalContent.html',
bindings: {
resolve: '<',
close: '&',
dismiss: '&'
},
controller: function () {
var $ctrl = this;
$ctrl.$onInit = function () {
$ctrl.items = $ctrl.resolve.items;
$ctrl.selected = {
item: $ctrl.items[0]
};
};
$ctrl.ok = function () {
$ctrl.close({ $value: $ctrl.selected.item });
};
$ctrl.cancel = function () {
$ctrl.dismiss({ $value: 'cancel' });
};
}
});`
I have a staff controller here that returns data from an API call, to populate the UI grid.`
var editButtonTemplate = '<div class="ui-grid-cell-contents"><button type=
"button" class="btn btn-xs btn-primary" ng-
click="grid.appScope.vm.editRow(grid, row)" <i class="fa fa-edit"></i>
</button></div>'
/*Staff Grid*/
app.controller('ApiStaffController', function ($scope, StaffService) {
$scope.gridOptions = {
data: 'Data',
enableFiltering: true,
showGroupPanel: true,
enableGridMenu: true,
resizable: true,
enableColumnResizing: true,
enableRowSelection: true,
enableRowHeaderSelection: false,
showGridFooter: true,
noUnselect: true,
multiSelect: false,
modifierKeysToMultiSelect: false,
noUnselect: true,
columnDefs: [{ field: 'person.forename', displayName: 'Forename' },
{ field: 'person.surname', displayName: 'Surname' },
{ field: 'person.dateofbirth', displayName: 'DOB' },
{ field: 'employmentStartDate', displayName: 'Employment Start Date' },
{ field: 'employmentEndDate', displayName: 'Employment End Date' },
{ name: 'edit', displayName: 'Edit', cellTemplate: editButtonTemplate },
{ name: 'delete', displayName: 'Delete', cellTemplate: '<button id="deleteBtn" type="button" class="btn-xs btn-danger fa fa-1x fa-trash-o" ng-click="$parent.$parent.deleteTeam(row.entity)"></button> ' }]
};
/*Gets all the staff records using the service*/
GetAllStaff();
function GetAllStaff() {
var promiseGet = StaffService.getAllStaff();
promiseGet.then(function (pl) { $scope.Staff = pl.data, $scope.Data = pl.data },
function (errorPl) {
$log.error('Error Getting Records.', errorPl);
});
}
});
I managed to resolve this by injecting: $uibModal into the staff controller like below:
app.controller('ApiStaffController', function ($scope, StaffService, $uibModal)
Then testing it by displaying the modal like this:
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
scope: $scope, //passed current scope to the modal
size: 'lg'
});
If there is a better / more flexible way of doing this I appreciate all feedback, thanks.

UI Bootstrap Modal don't close. AngularJS

I was looking for this question on forum and the solution dosn't worked for me, so...
The only way to close the modal is clicking outside of modal, or press ESC on keyboard..
Here is my modal controller:
app.controller('ModalCtrl', function($scope, $uibModal) {
$scope.items = [{}]
$scope.showModal = function(selectedItem) {
var uibModalInstance = $uibModal.open({
windowTopClass: 'modal fade ql-modal',
templateUrl : 'modalContent.html',
controller : function($scope, $uibModalInstance, $uibModal, item){
$scope.item = item;
},
resolve: {
item: function(){
return selectedItem;
}
} // empty storage
});
uibModalInstance.result.then(function(selectedItem){
$scope.selected = selectedItem;
$scope.cancel = function(){
$uibModalInstance.dismiss('cancel');
};
});
};
});
And here is my modal on HTML:
<script type="text/ng-template" id="modalContent.html">
<!-- Modal -->
<!--Content-->
<div class="modal-content">
<!--Header-->
<div class="modal-header">
<button type="button" class="close" data-dismiss="MyModal" aria-label="Close" ng-click="cancel()">
<span aria-hidden="true">×</span>
</button>
...................................
<div class="modal-footer">
<button type="button" class="btn btn-primary" ng-click="cancel()">Close</button>
</div>
</div>
<!--/.Content-->
<!--/Modal-->
</script>
I followed every answer, fiddle, plnkr, but i cannot make it work.
Just move a cancel() method from uibModalInstance.result.then to
your modal controller:
var uibModalInstance = $uibModal.open({
windowTopClass: 'modal fade ql-modal',
templateUrl : 'modalContent.html',
controller : function($scope, $uibModalInstance, $uibModal, item){
$scope.item = item;
$scope.cancel = function(){
$uibModalInstance.dismiss('cancel');
};
},
resolve: {
item: function(){
return selectedItem;
}
} // empty storage
});

ui-bootstrap how to get the scope in view aliased

View calling modal
I have this code you should: open a modal bringing the data within the controller being used by the angular-ui-bootstrap. But it is not getting the result of the "item" that is selected.
in my controller:
function EntidadesCtrlFn(EntidadeService, $uibModal, $log) {
var vm = this;
vm.animationsEnabled = true;
vm.modalEdit = function(size, selectedEntidade) {
var modalInstance = $uibModal.open({
animation: vm.animationsEnabled,
templateUrl: './app/modulos/entidades/views/edit-entidades.html',
controller: function($scope, $uibModalInstance, entidade) {
vm.entidade = entidade;
},
controllerAs: 'vm',
bindToController: true,
size: size,
resolve: {
entidade: function() {
return selectedEntidade;
}
}
});
modalInstance.result.then(function(selectedItem) {
vm.selected = selectedItem;
}, function() {
console.log('Modal dismissed.result.');
$log.info('Modal dismissed at: ' + new Date());
});
};
in view of list:
<div class="row" ng-controller="EntidadesCtrl as vm">
...
<button class="btn btn-default" ng-click="vm.modalEdit('lg', entidade)" type="button">
Editar
</button>
...
This modal opens, but does not bring the contents of:
controller: function($scope, $uibModalInstance, entidade) {
vm.entidade = entidade;
},
TemplateUrl:
<section ng-controller="EntidadesCtrl as vm">
{{vm}}
<div class="modal-header">
<h3 class="modal-title">Editando entidade</h3>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()" type="button">OK</button>
<button class="btn btn-warning" ng-click="cancel()" type="button">Cancel</button>
</div>
</section>
Solved.
I ended up forgetting to pass "this" in the controller ;
Sorry about that.
In the controller modal:
controller: function($uibModalInstance, entidade) {
var vm = this;
vm.entidade = entidade;
},

Toggling a Twitter Bootstrap (3.x) Modal using AngularJS

I've been trying to get a Bootstrap Model to be hidden on load, and then show it after clicking a button, but have been unsuccessful so far. I am pretty new to AngularJS so bear with me if I'm not doing this correctly. Here's what I've got so far:
Modal Angular Directive (modal.js):
angular.module('my.modal', ['modal.html'])
.directive('myModal', function () {
return {
restrict: 'E',
transclude: true,
replace: false,
templateUrl: 'modal.html',
link: function(scope, element, attrs) {
element.modal('hide')
scope.toggleModal = function() {
if (attrs.showModal === true) {
element.modal('hide')
attrs.showModal = false
} else {
element.modal('show')
attrs.showModal = true
}
}
}
};
});
Modal Template (modal.html):
<div id="{{id}}" showModal="false" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<div class="content" ng-transclude></div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="showModal = false">Cancel</button>
</div>
</div>
</div>
</div>
And finally, the button to toggle the modal (index.html):
...
<my-modal>
<p>Some content</p>
</my-modal>
<button class="btn btn-default" type="button" ng-click="toggleModal()">Toggle me!</button>
...
All this does is show the modal on page load (between my header and all the other content, so it's not floating above anything) and the toggle button does not work.
I've managed to get it working by using the Bootstrap 3 Modal properties and dynamically changing styling and classes of the modal directive based on it's show or hide state, though there are no animations:
Modal Angular Directive (modal.js):
angular.module('my.modal', ['modal.html'])
.directive('myModal', [function () {
return {
restrict: 'E',
transclude: true,
replace: false,
templateUrl: 'modal.html',
controller: 'ModalCtrl',
link: function(scope, element, attrs) {
if (attrs.title === undefined) {
scope.title = 'Modal Title Placeholder';
} else {
scope.title = attrs.title;
}
scope.$watch('showModal', function (value) {
if (value) {
scope.displayStyle = 'block';
scope.modalFadeIn = 'in';
} else {
scope.displayStyle = 'none';
scope.modalFadeIn = '';
}
});
}
};
}).controller('ModalCtrl', ['$scope', function ($scope) {
$scope.toggleModal = function() {
$scope.showModal = !$scope.showModal;
};
$scope.$open = function() {
$scope.showModal = true;
};
$scope.$close = function() {
$scope.showModal = false;
};
});
Modal Template (modal.html):
<div role="dialog" tabindex="-1" class="modal fade" ng-init="showModal = false" ng-show="showModal" ng-style="{display: displayStyle}" ng-class="modalFadeIn">
<div class="modal-backdrop fade in" style="height: 100%"> </div>
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">{{title}}</h3>
</div>
<div class="modal-body">
<div class="content" ng-transclude></div>
</div>
</div>
</div>
</div>
The call to open the modal can be done using the open or toggleModal function. A custom button needs to be placed in the modal to close the modal.

Angular placing functions

I'm using the angular-google-maps library in my project. I have used a directive to load a custom google maps menu. The goal is to obviously reuse the directive. In the menu are a couple of buttons which when clicked should all carry out a function. I'm still trying to get my head around on how to do that, so here is my problem:
I would like to pan the map to its original position when the button "Home" is clicked. Normally that is just done with ng-click and the function is placed within the scope of the controller. With the directive I'm confused. Where should I place the "home()" function? Directive? Directive controller? Controller? I hope this makes any sense?!?!
HTML:
<div class="map_canvas">
<google-map center="map.center" zoom="map.zoom" draggable="true">
<marker ng-repeat="m in map.markers" coords="m" icon="m.icon" click="onMarkerClicked(m)">
<marker-label content="m.name" anchor="50 0" class="marker-labels"/>
<window ng-cloak coords="map.center" isIconVisibleOnClick="false" options="map.infowindows.options">
<p>This is an info window at {{ m.latitude | number:4 }}, {{ m.longitude | number:4 }}!</p>
<p class="muted">My marker will stay open when the window is popped up!</p>
</window>
</marker>
<map-custom-control position="google.maps.ControlPosition.TOP_CENTER" control-template="../templates/gmaps/main_menu.html" control-click=""></map-custom-control>
</google-map>
</div>
Template:
<div class="gmaps-menu">
<div class="gmaps-row">
<button type="button" class="btn btn-default"><img class="glyphicon-custom" src="../img/icons/glyphicons/glyphicons_020_home.png" ng-click="home()"></button>
<button type="button" class="btn btn-default"><img class="glyphicon-custom" src="../img/icons/glyphicons/glyphicons_349_fullscreen.png"></button>
<button type="button" class="btn btn-default"><img class="glyphicon-custom" src="../img/icons/glyphicons/glyphicons_096_vector_path_polygon.png"></button>
<button type="button" class="btn btn-default"><img class="glyphicon-custom" src="../img/icons/glyphicons/glyphicons_030_pencil.png"></button>
</div>
</div>
Directive:
AppDirectives.directive('mapCustomControl', ['$log', '$timeout', '$http', '$templateCache', 'google', 'GMapsLib' ,function ($log, $timeout, $http, $templateCache, google,GMapsLib) {
return {
restrict: 'E',
replace: true,
require: '^googleMap',
link: function(scope,element,attr,mapCtrl){
if (!angular.isDefined(attr.controlTemplate)) {
$log.error('map-custom-control: could not find a valid control-template property!');
return;
}
var templateUrl = attr.controlTemplate;
var position = google.maps.ControlPosition.TOP_CENTER;
if (angular.isDefined(attr.position)) {
var EVAL_IS_OK_WE_CONTROL_THE_INPUT = eval;
position = EVAL_IS_OK_WE_CONTROL_THE_INPUT(attr.position);
}
$timeout(function() {
var map = mapCtrl.getMap();
var controlDiv = document.createElement('div');
controlDiv.style.padding = '5px';
controlDiv.style.width = 'auto';
controlDiv.marginLeft = 'auto';
controlDiv.marginRight = 'auto';
$http.get(templateUrl, {cache: $templateCache})
.success(function(html) {
controlDiv.innerHTML = html;
})
.then(function (/*response*/) {
map.controls[position].push(controlDiv);
if (angular.isDefined(attr.controlClick)) {
google.maps.event.addDomListener(controlDiv, 'click', function() {
scope.$apply(attr.controlClick);
});
}
}
);
});
}
};
}]);
You can pass the scope function that has to be executed on the controller:
HTML
<div ng-app="app" ng-controller="sampleCtrl">
<maps-custom-control click-handler="alertMe()"></maps-custom-control>
</div>
JS
var app = angular.module('app', []);
app.directive('mapsCustomControl', function() {
return {
restrict: 'EA',
replace: true,
scope: {
clickHandler: '&'
},
template: '<div style="width: 100px; height:100px; background-color: red;" ng-click="clickHandler()"></div>'
};
});
app.controller('sampleCtrl', function ($scope) {
$scope.alertMe = function () {
window.alert('Refresh gMaps control');
};
});
Since we pass the alertMe function, this is the function that will get executed, I hope this makes sense?
Fiddle
A small remark on your code, it would be better if you get the template as follows:
app.directive('..', function() {
return {
template: '<div ng-include="getTemplate()"></div>',
link: function(scope, element, attr) {
scope.getTemplate = function() {
return this.attr.controlTemplate;
}
}
};
});
This way you don't need to do any strange ajax calls. Just add all the mark-up in your template and include it. don't make it necessary hard :-)

Resources