AngularJS directive to add content after element and trigger element click - angularjs

I'm trying to create a very simple directive to ask confirmation on a button click.
The following html:
<button kr-confirm>Delete</button>
Should compile into:
<button kr-confirm>Delete</button>
<span ng-show="vm.isOpen">
Are you sure?
<span class="btn btn-sm btn-danger">Yes</span>
<span class="btn btn-sm btn-secondary">No</span>
</span>
I wanted to handle this in templateUrl, but could not find an option to add template after element.
I ended up adding DOM in link function and calling element.on('click') but this doesn't seem to work.
Based on HTML and anticipated result, how would I go about implementing this?
Best case would be if it could be solved with templateUrl.
See my current fiddle:
https://jsfiddle.net/kraaness/4rn8ycb3/

You should create a component that will provide you with the desired functionality. See a quick <confirmation-button> component below.
angular.module('app', [])
.component('confirmationButton', {
bindings: {
onConfirm: '&'
},
template: '<button ng-click="$ctrl.confirm = true">Delete</button>' +
'<div ng-show="$ctrl.confirm">Are you sure?' +
'<button ng-click="$ctrl.onConfirm(); $ctrl.confirm = false">Yes</button>' +
'<button ng-click="$ctrl.confirm = false">No</button></div>'
})
.run(function($rootScope) { // using $rootScope just for sake of the demo
$rootScope.delete = function() {
alert("Oh no!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="app">
<confirmation-button on-confirm="delete()"></confirmation-button>
</div>

Related

Angular Modal: add template from another html

I have a modal template in another html file but after the page was loaded first time modal window opens without a content, second time it's all ok. How can this be fixed?
Here's the plunker http://plnkr.co/edit/lw056nAaU7BfqIVZSddb?p=preview
//Open modal on main page with:
<div ng-controller="ModalDemoCtrl">
<button type="button" class="btn btn-default" ng-click="open()">Open me!</button>
<button type="button" class="btn btn-default" ng-click="open('lg')">Large modal</button>
<button type="button" class="btn btn-default" ng-click="open('sm')">Small modal</button>
<button type="button" class="btn btn-default" ng-click="toggleAnimation()">Toggle Animation ({{ animationsEnabled }})</button>
<div ng-show="selected">Selection from a modal: {{ selected }}</div>
You should not wrap your template with <script type="text/ng-template" id="myModalContent.html"></script>.
Ui-modal expects direct HTML here.
If you need to use ng-template, you should insert the ng-template script tag in your index.html (or anywhere else but it should be loaded in your page) and open your modal with template instead of templateUrl this way :
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
template: "<div ng-include src=\"'myModalContent.html'\"></div>",
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
Maybe you can use $templateCache in this case instead to load the template from another file. I don't know why you have this issue but this solved the problem for me.
Maybe you are not looking for something like that, since this increase the JS file size and sometimes this template will never be used.
angular.module('ui.bootstrap.demo').run(['$templateCache', function ($templateCache) {
$templateCache.put('myModalContent.html',
'Hello World'
);
}]);
What do you think?
EDIT: #Pierre Maoui answer seems more adequate for me based on the question.

Can't create a popover with custom template

First I tried using angular-ui
<span popover-template="removePopover.html" popover-title="Remove?" class="glyphicon glyphicon-remove cursor-select"></span>
here the template is not included and no errors are provided in console. As I undestood from previous questions this capability is still in development (using v0.13.0).
Then I tried using bootstrap's popover
<span delete-popover row-index={{$index}} data-placement="left" class="glyphicon glyphicon-remove cursor-select"></span>
This is included to popover
<div id="removePopover" style="display: none">
<button id="remove" type="button" ng-click="removeElement()" class="btn btn-danger">Remove</button>
<button type="button" ng-click="cancelElement()" class="btn btn-warning">Cancel</button>
</div>
This is the managing directive
app.directive('deletePopover', function(){
return{
link: function(scope, element, attrs) {
$(element).popover({
html : true,
container : element,
content: function() {
return $('#removePopover').html();
}
});
scope.removeElement = function(){
console.log("remove"); //does not get here
}
scope.cancelElement = function(){
console.log("cancel"); //does not get here
}
}
};
});
In case of bootstrap's popover the scope is messed up. cancelElement() call does not arrive in directive neither the parent controller.
If anyone could help me get atleast on of these working it would be great.

Compiling Another Directive inside a Directive not working

I'm developing a blog website and currently working on a post creator. The post creator will eventually allow a user to add HTML elements to their post and edit them when needed, before submitting the post.
So far, a user can add a Header or Rich Text to their post. I'm working on rendering these components based on content information retrieved from the backend, as such:
<div ng-repeat="component in components track by $index">
<editable type="component.type" model="component.content"></editable>
</div>
The editable directive looks like the following:
(function() {
'use strict';
angular.module('blog')
.directive('editable', directive);
directive.$inject = ['$compile'];
function directive($compile) {
return {
restrict: 'E',
templateUrl: 'components/editable/editable.html',
scope: {
type: '=',
model: '='
},
link: function(scope, element) {
scope.editing = false;
scope.currentModel = scope.model;
var viewTemplate, editTemplate;
switch(scope.type) {
case 'header':
viewTemplate = '<h2 ng-show="!editing">{{currentModel}}</h2>';
editTemplate = '<input ng-show="editing" type="text" class="form-control" ng-model="model">';
compileTemplate(viewTemplate, editTemplate);
break;
case 'richtext':
viewTemplate = '<div ng-show="!editing">{{currentModel}}</div>';
editTemplate = '<summernote ng-show="editing" ng-model="model" height="300"></summernote>';
compileTemplate(viewTemplate, editTemplate);
break;
default:
break;
}
function compileTemplate(viewTemplate, editTemplate) {
var viewTemplateCompiled, editTemplateCompiled;
viewTemplateCompiled = $compile(angular.element(viewTemplate))(scope);
editTemplateCompiled = $compile(angular.element(editTemplate))(scope);
element.find('view').replaceWith(viewTemplateCompiled);
element.find('edit').replaceWith(editTemplateCompiled);
}
scope.toggleEditMode = function(saveChanges) {
scope.editing = !scope.editing;
if (saveChanges) {
scope.currentModel = scope.model;
}
}
}
}
}
}());
The template looks like the following:
<div class="row">
<div class="col-md-8">
<view></view>
<edit></edit>
</div>
<div class="col-md-4">
<span class="pull-right">
<button ng-show="editing" class="btn btn-success" ng-click="toggleEditMode(true)"><span class="glyphicon glyphicon-ok"></span></button>
<button ng-show="editing" class="btn btn-danger" ng-click="toggleEditMode(false)"><span class="glyphicon glyphicon-remove"></span></button>
<button ng-show="!editing" class="btn btn-warning" ng-click="toggleEditMode(true)"><span class="glyphicon glyphicon-edit"></span></button>
</span>
</div>
</div>
Here's how the website looks like in "view" mode, with the HTML for summernote inspected:
When the "edit" button is clicked (yellow one on the right with the icon), The second line should appear in a summernote editor, but the editor never shows up:
I've noticed that the summernote editor is never inserted after compiling (you'll see that it's not there in the developer tools/element inspector). Perhaps this is the issue? If so, is there a way to fix it?
P.S.: I can create a Plunkr on request.
function compileTemplate(viewTemplate, editTemplate) {
var viewTemplateCompiled = angular.element(viewTemplate),
editTemplateCompiled = angular.element(editTemplate);
element.find('view').replaceWith(viewTemplateCompiled);
element.find('edit').replaceWith(editTemplateCompiled);
$compile(viewTemplateCompiled)(scope);
$compile(editTemplateCompiled)(scope);
}

ui.bootstrap modal loading html but not showing anything

Its loading opening modal and also loading template specified. But not showing anything.
Check out the demo here : http://demo.hupp.in/food-admin
Go to [Products] and Search EnegiKcal >= 3500. Then click on manage. It will open pop up but template content is not loaded.
Also one other thing I noticed is that it returns HTTP 304 for template sometimes.
This is how I open modal :
/** Open Modal For add edit tags */
$scope.open = function (productId) {
var modalInstance = $modal.open({
templateUrl: 'views/some.html',
controller: tagsModalInstanceCtrl,
size: 'lg'
});
modalInstance.result.then(function (msg) {
}, function () {
// $log.info('Modal dismissed at: ' + new Date());
});
};
var tagsModalInstanceCtrl = function ($scope, $modalInstance) {
$scope.ok = function () {
$modalInstance.close("hi");
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
Here is template code :
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<h3>Well, Hello there!</h3>
</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>
Ok, it is pretty strange but it seems that your template is based on the master branch of https://github.com/angular-ui/bootstrap/blob/master/template/modal/window.html
and your sources on the tag 0.11.
https://github.com/angular-ui/bootstrap/blob/0.11.0/src/modal/modal.js
It is visible when you type $('.modal-content') in the console, you will see that it needs a modal-transclude directive, but in the sources there is no trace of this directive. Because, on 0.11 it directly uses the ng-transclude directive which is part of angular.
So, your code is correct, but the lib is not, try retrieving a correct version of it (maybe the last build of their repo is broken)
As a matter of fact, I did have a similar problem when switching to angularjs v1.2. The formerly working dialog didn't show, just like yours. Had to change the structure to look something like this to make it visible again:
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div class="row">
<div class="col-lg-9">
<h3>{{header}}</h3>
</div>
</div>
</div>
<div class="modal-body">
<form name = "kontoForm" szp-focus="sifra">
<!-- Šifra -->
<szp-input id="sifra" text="Šifra" place-holder="šifra" value="konto.sifra" required="!konto.sifra"></szp-input>
<!-- Naziv -->
<szp-input id="naziv" text="Naziv" place-holder="naziv" value="konto.naziv" required="!konto.naziv"></szp-input>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-hide="!kontoForm.$valid || (mode == 'edit')" ng-click="okContinue()">OK i nastavi</button>
<button class="btn btn-primary" ng-hide="!kontoForm.$valid" ng-click="ok()">OK i zatvori</button>
<button class="btn btn-warning" ng-click="cancel()">Odustani</button>
</div>
</div>
</div>
I had to wrap everythin in a div with a modal-content class to make it work.
include .map files for jquery and angular in your /js folder .may be that will help
I have experienced this off and on for some reason as well.
I solved it by adding a CSS statement, after doing an inspection via Chrome's tools I found that for some reason the modal display was still set to hidden.
.modal {
display: block;
}
Take a look this link.
vm_main.showModal = {
mostrarErrores : false,
showModal : function(jsonError) {
var options={
tituloModal: jsonError.titleModal,
textoPrincipal: jsonError.mainMessage,
textoBtnAceptar: "Aceptar",
accionBtnAceptar: "vm_popup.cerrarPopup()",
};
commonPopUpService.getDisclaimerGeneric($scope, 'commonPopUpController', options);
}
};
http://plnkr.co/edit/EYDEG5WSmNwxQflsB21T?p=preview
I think will help you on how load a simple dinamic html as a modal.
Regards

Invoking modal window in AngularJS Bootstrap UI using JavaScript

Using the example mentioned here, how can I invoke the modal window using JavaScript instead of clicking a button?
I am new to AngularJS and tried searching the documentation here and here without luck.
Thanks
OK, so first of all the http://angular-ui.github.io/bootstrap/ has a <modal> directive and the $dialog service and both of those can be used to open modal windows.
The difference is that with the <modal> directive content of a modal is embedded in a hosting template (one that triggers modal window opening). The $dialog service is far more flexible and allow you to load modal's content from a separate file as well as trigger modal windows from any place in AngularJS code (this being a controller, a service or another directive).
Not sure what you mean exactly by "using JavaScript code" but assuming that you mean any place in AngularJS code the $dialog service is probably a way to go.
It is very easy to use and in its simplest form you could just write:
$dialog.dialog({}).open('modalContent.html');
To illustrate that it can be really triggered by any JavaScript code here is a version that triggers modal with a timer, 3 seconds after a controller was instantiated:
function DialogDemoCtrl($scope, $timeout, $dialog){
$timeout(function(){
$dialog.dialog({}).open('modalContent.html');
}, 3000);
}
This can be seen in action in this plunk: http://plnkr.co/edit/u9HHaRlHnko492WDtmRU?p=preview
Finally, here is the full reference documentation to the $dialog service described here:
https://github.com/angular-ui/bootstrap/blob/master/src/dialog/README.md
To make angular ui $modal work with bootstrap 3 you need to overwrite the styles
.modal {
display: block;
}
.modal-body:before,
.modal-body:after {
display: table;
content: " ";
}
.modal-header:before,
.modal-header:after {
display: table;
content: " ";
}
(The last ones are necessary if you use custom directives) and encapsulate the html with
<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">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
Open modal windows with passing data to dialog
In case if someone interests to pass data to dialog:
app.controller('ModalCtrl', function($scope, $modal) {
$scope.name = 'theNameHasBeenPassed';
$scope.showModal = function() {
$scope.opts = {
backdrop: true,
backdropClick: true,
dialogFade: false,
keyboard: true,
templateUrl : 'modalContent.html',
controller : ModalInstanceCtrl,
resolve: {} // empty storage
};
$scope.opts.resolve.item = function() {
return angular.copy(
{name: $scope.name}
); // pass name to resolve storage
}
var modalInstance = $modal.open($scope.opts);
modalInstance.result.then(function(){
//on ok button press
},function(){
//on cancel button press
console.log("Modal Closed");
});
};
})
var ModalInstanceCtrl = function($scope, $modalInstance, $modal, item) {
$scope.item = item;
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
Demo Plunker
The AngularJS Bootstrap website hasn't been updated with the latest documentation. About 3 months ago pkozlowski-opensource authored a change to separate out $modal from $dialog commit is below:
https://github.com/angular-ui/bootstrap/commit/d7a48523e437b0a94615350a59be1588dbdd86bd
In that commit he added new documentation for $modal, which can be found below:
https://github.com/angular-ui/bootstrap/blob/d7a48523e437b0a94615350a59be1588dbdd86bd/src/modal/docs/readme.md.
Hope this helps!
Quick and Dirty Way!
It's not a good way, but for me it seems the most simplest.
Add an anchor tag which contains the modal data-target and data-toggle, have an id associated with it. (Can be added mostly anywhere in the html view)
Now,
Inside the angular controller, from where you want to trigger the modal just use
angular.element('#myModalShower').trigger('click');
This will mimic a click to the button based on the angular code and the modal will appear.
Different version similar to the one offered by Maxim Shoustin
I liked the answer but the part that bothered me was the use of <script id="..."> as a container for the modal's template.
I wanted to place the modal's template in a hidden <div> and bind the inner html with a scope variable called modal_html_template
mainly because i think it more correct (and more comfortable to process in WebStorm/PyCharm) to place the template's html inside a <div> instead of <script id="...">
this variable will be used when calling $modal({... 'template': $scope.modal_html_template, ...})
in order to bind the inner html, i created inner-html-bind which is a simple directive
check out the example plunker
<div ng-controller="ModalDemoCtrl">
<div inner-html-bind inner-html="modal_html_template" class="hidden">
<div class="modal-header">
<h3>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 class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</div>
<button class="btn" ng-click="open()">Open me!</button>
<div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>
inner-html-bind directive:
app.directive('innerHtmlBind', function() {
return {
restrict: 'A',
scope: {
inner_html: '=innerHtml'
},
link: function(scope, element, attrs) {
scope.inner_html = element.html();
}
}
});

Resources