bootstrap 5 popover with html content - javascript

I am trying to get separate the bootstrap5 popover content from the HTML attributes like you can do with other components, but I can't get it to work.
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function(popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
})
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<a type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover">Click to toggle popover</a>
<div id="customdiv" style="display: none">
<h1> popover </h1>
</div>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>

Nobody answered properly with simple JavaScript without jQuery dependency. It's important because Bootstrap 5 doesn't depend on jQuery anymore.
HTML:
<a class="btn btn-link" data-bs-toggle="popover" data-bs-placement="bottom" data-bs-content-id="popover-content" tabindex="0" role="button">
Open Popover
</a>
<div id="popover-content" class="d-none">
Popover content with <strong>HTML</strong>.
</div>
JavaScript:
const list = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
list.map((el) => {
let opts = {
animation: false,
}
if (el.hasAttribute('data-bs-content-id')) {
opts.content = document.getElementById(el.getAttribute('data-bs-content-id')).innerHTML;
opts.html = true;
}
new bootstrap.Popover(el, opts);
})

var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl,{html: true})
});

None of the answers really offered me a complete solution where the popover does not appear until the data-bs-trigger event happen so this is my solution:
Element that when hovering on will have popover:
<a class="btn btn-question-tag"
data-bs-toggle="popover"
data-bs-trigger="hover focus"
data-content-id="popover-27"
href="#">
element to trigger popover
</a>
Element that its inner html will be in the popover that appears.
<div style="display: none;" id="popover-27">
<div class="popover" role="tooltip">
This is the
</div>
</div>
javascript:
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
const popoverId = popoverTriggerEl.attributes['data-content-id'];
if (popoverId) {
const contentEl=$(`#${popoverId.value}`).html();
return new bootstrap.Popover(popoverTriggerEl, {
content: contentEl,
html: true,
});
}else{//do something else cause data-content-id isn't there.
}
}

There is a simple way to put an html element in popover container
you must put the html element directly in data-bs-content tag,
and set the data-bs-html="true" to parse that content as html
and also disable the sanitize to make the content readable as html
this code works for me try it too.
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function(popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
})
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<a type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover"
data-bs-html="true" data-bs-sanitize="false"
data-bs-content='<div class="popover fs-6" role="tooltip">
<div class="popover-body">Providing your birthday helps make sure you get the right Facebook experience for your age. If you want to change who sees this, go to the About section of your profile. For more details, please visit our Data Policy.</div></div>'>Click to toggle popover</a>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>

Bootstrap v5.2.0 and laravel 8 in app.js
document.addEventListener('DOMContentLoaded', function() {
var element = document.getElementById('myPopover');
if (element) {
var popover = new bootstrap.Popover(element, {
container: 'body',
html: true,
content: function() {
return document.getElementById('popover-content').innerHTML;
},
});
}
});
Laravel blade
<a tabindex="0" type="button" data-bs-toggle="popover" data-bs-placement="bottom" aria-label="Share this article socially" id="myPopover" >
<img src="{{asset('layout/icon_return.svg')}}" alt="share icon">
</a>
<div class="pop-in" id="popover-content" style="display:none;"> <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
<div class="btn-group" role="group" aria-label="First group">
<a class="btn btn-secondary" href="https://www.facebook.com/sharer.php?u={{ $item->url }}" target="_blank" rel="noopener" type="button" ><img src="{{asset('layout/facebook.svg')}}" alt="Share Page on Facebook" ></a>
<a class="btn btn-secondary" href="https://twitter.com/intent/tweet?url={{ $item->url }}%2F&text={{ $item->title }}.&hashtags=css,html" target="_blank" rel="noopener" type="button" ><img src="{{asset('layout/twitter.svg')}}" alt="Share Page on Twitter"></a>
<a class="btn btn-secondary" href="https://www.linkedin.com/shareArticle?mini=true&url={{ $item->url }}%2F&item={{ $item->title }}" target="_blank" rel="noopener" type="button" ><img src="{{asset('layout/linkedin.svg')}}" alt="Share Page on LinkedIn" ></a>
</div>
</div>
</div>

var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
})
var popover = new bootstrap.Popover(document.querySelector('.element'), {
trigger: 'hover',
html: true,
content:function () {
return '<label>Test</label>';
},
})

Although the above answers looks fine but there is small correction here. Content option in bootstrap 5 is not working with innerHTML as it expects the type element/string/function to get the content from.
So as usual, first we will need to create div for the content with some id and then wrap it inside hidden div as this will be also shown in main flow. And then with html and content options provided by bootstrap popover, we will insert the custom popover content.
Also, instead of innerHTML, we will directly have document.getElementById('mypopover-content') as the popover content element to show as the content (and not document.getElementById('mypopover-content').innerHTML).
var popover = new bootstrap.Popover(document.querySelector('.example-popover'), {
container: 'body',
html: true,
content: document.getElementById('mypopover-content'),
})
body {
margin: 10px !important;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js"></script>
<a class="btn btn-primary example-popover" role="button" tabindex="0" title="Content demonstration popover"
>Trigger popover with other html content</a>
<div hidden>
<div id="mypopover-content">
<p>This is the custom popover html content that should be inserted into my example popover</p>
<button type="button" class="btn btn-primary">and the button as well</button>
</div>
</div>

var hideDiv = document.getElementsByClassName('hide')[0].style.visibility = 'hidden'
var popoverBtn = document.getElementById('btn-action')
var popover = new bootstrap.Popover(popoverBtn, {
placement: 'bottom',
html: true,
content: function() {
return document.getElementById('id-content-div');
}
})
var showDiv = document.getElementsByClassName('hide')[0].style.visibility = 'visible'
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<a type="button" class="btn btn-lg btn-danger" id="btn-action">Click to toggle popover</a>
<div id="id-content-div" class="hide">
<h1> popover </h1>
<p>Hello popover world</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>

$(function() {
var options = {
html: true,
title: "Optional: HELLO(Will overide the default-the inline title)",
//html element
content: $("#popover-content")
//Doing below won't work. Shows title only
//content: $("#popover-content").html()
}
var exampleEl = document.getElementById('example')
var popover = new bootstrap.Popover(exampleEl, options)
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.5.0/font/bootstrap-icons.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="popover-content">
<div class="input-group">
<input type="text" class="form-control form-control-sm" placeholder="Search" name="search">
<div class="input-group-btn">
<button class="btn btn-danger" type="submit">
<i class="bi bi-search"></i>
</button>
</div>
</div>
<div class="col-sm-8"></div>
<button class="btn btn-success m-3">Button</button>
<input type="submit" class="btn btn-danger" placeholder="Button red">
</div>
<a id="example" tabindex="0" class="btn btn-lg btn-danger" role="button" data-bs-toggle="popover" title="Default: Html inside popover" data-bs-content="And here's some amazing content. It's very engaging. Right? This is default, but Can be empty">Html inside popover</a>

You can't have a zero length title and content. From the Bootstrap docs...
"Zero-length title and content values will never show a popover."
<a type="button" class="btn btn-lg btn-danger"
data-bs-toggle="popover"
data-bs-title="Hello">Click to toggle popover</a>
Demo

Related

Change button icon with animation

I am using bootstrap icons and javascript and I would like to know how can I change the icon in an animated way?
toClipboard: function (refElementName, sender) {
let btn = $(sender);
let btnIcon = btn.find("i")
$("[name='" + refElementName + "']").select()
document.execCommand("copy")
btn.fadeOut(400)
btnIcon.attr("class", "bi bi-clipboard-check")
btn.delay(400)
btnIcon.attr("class", "bi bi-clipboard")
}
html
<div class="col position-relative">
<textarea name="textObs" rows="5" class="form-control" placeholder="Observações"></textarea>
<a class="btn btn-primary" id="copy" onclick="toClipboard('textObs', this)"><i class="bi bi-clipboard"></i></a>
</div>
I tried this, but it doesn't work as expected ... the animation happens but in the end the button is without icon
https://jsfiddle.net/r06s5ctn/
Is this what you're looking for?
On click, fade out icon, then set a timeout to change the icon class once it's faded out, then fade the icon back in.
function toClipboard(refElementName, sender) {
let btn = $(sender);
let btnIcon = btn.find("i")
$("[name='" + refElementName + "']").select()
document.execCommand("copy")
btn.fadeOut(400)
setTimeout(function() {
btnIcon.removeClass("bi-clipboard").addClass("bi-clipboard-check")
}, 400)
btn.fadeIn(400)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.4.1/font/bootstrap-icons.min.css">
<div class="col position-relative">
<textarea name="textObs" rows="5" class="form-control" placeholder="Observações"></textarea>
<a class="btn btn-primary" id="copy" onclick="toClipboard('textObs', this)"><i class="bi bi-clipboard"></i></a>
</div>
Alloha !
To change de icon of the button, you just need to use .html from jquery like this :
btn.fadeOut(400)
btnIcon.html("<i class="bi bi-clipboard-check"></i>")
btn.delay(400)
btnIcon.attr("<i class="bi bi-clipboard"></i>")
Have a good day!

jquery hide method hides div but then div reappears

I have the following code where I want to hide the closest grouping div. When I click the delete button, the div disappears but then comes back (added 600 so I could see this).
I have researched and found others saying to use event.preventDefault, return false; and add href”#!’ to the <a> tag. None seem to work. I changed the .hide() to .remove() and It works, but I won't just want to hide the div and use it later in the post model binding
#model Durendal.Core.ViewModels.RoleViewModel
<div class="d-flex flex-row grouping">
<div class="flex-grow-1" style="overflow-x: auto;">
#(Html.Kendo().DropDownListFor(m => m.Id)
.DataTextField("Name")
.DataValueField("Id")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%;" })
.Height(290)
.Filter(FilterType.Contains)
.AutoWidth(true)
.DataSource(source =>
{
source.Custom()
.Transport(transport => transport
.Read(read => read
.Action("GetRoles", "DataApi", new { Area = "Shared" })));
})
)
</div>
<div class="">
<a href="#!" class="btn btn-sm btn-outline-danger waves-effect remove-grouping-button">
<i class="fas fa-times"></i>
</a>
</div>
<script type="text/javascript">
(function () {
$('.remove-grouping-button').click(function (event) {
event.preventDefault();
$(this).closest('.grouping').hide(600);
return false;
});
})();
</script>
</div>
This should hide the div but it reappears
Your code works - some other code must make it re-appear.
I only post this for demonstration and will delete it when you have seen it.
Please do not vote up or accept as answer and No need to vote down either
$(function() {
$('.remove-grouping-button').click(function(event) {
event.preventDefault(); // cancel anchor click
$(this).closest('.grouping').hide(600);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="d-flex flex-row grouping">
<div class="flex-grow-1" style="overflow-x: auto;">
Some Kendo dropdown
</div>
<div class="">
<a href="#!" class="btn btn-sm btn-outline-danger waves-effect remove-grouping-button">
<i class="fas fa-times"></i>
</a>
</div>
</div>

Magnific Pop up wont close when you press Cancel on the Modal

I am using Magnific Pop up on a project, currently I have it on a ASP MVC project as a Modal:
Modal
div id="js_DeleteNewSongsPopup" class="theme-primary ajax-form popup-basic admin-form mfp-with-anim modalPopup">
<div class="panel">
<div class="panel-heading">
<span class="panel-title">
<i class="fa fa-ban "></i>Reject Selected Song
</span>
</div>
#* Information Body *#
<div class="panel-body p25">
<div class="section row">
<div class="col-md-12 text-center">
<h3>
Are you sure you want to <b class="text-danger">reject</b> the selected Songs?
</h3>
<p>
Please note, these will be <b class="text-danger">deleted</b> and no longer accessable
</p>
</div>
</div>
</div>
#* Form Body *#
<div class="panel-footer">
<div class="text-center">
<fieldset>
<input type="button" class="btn btn-primary js_CancelForm" value="Cancel" data-bind="click: function(){ $.magnificPopup.close(); }">
<input type="button" class="btn btn-danger js_DeleteNewSongsButton" value="Delete" data-bind="click: $root.submitDeleteNewSongs">
</fieldset>
</div>
</div>
</div>
<button title="Close (Esc)" type="button" class="mfp-close">×</button>
JavaScript
/* Delete New Songs Popup*/
$(document).on("click",
".js_DeleteNewSongs",
function (e) {
e.preventDefault();
var popup = $("#js_DeleteNewSongsPopup");
$.magnificPopup.open({
removalDelay: 500, //delay removal by X to allow out-animation,
items: {
src: $(popup)
},
callbacks: {
beforeOpen: function (e) {
this.st.mainClass = 'mfp-slideUp';
},
close: function () {
}
},
midClick: true
// allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
});
return false;
});
Any ideas as there is no console errors being reported. I am also unsure why it is working on another page, when the mark-up is identical
Try:
$('body').removeClass('panel-body p25');
Or
$('body').removeClass('theme-primary ajax-form popup-basic admin-form mfp-with-anim modalPopup');
Basically you need to remove the "modal" class.
Ended up using:
$('.js_CancelForm').on("click", function () {
$.magnificPopup.close();
});
Now the Popup closes as expected.

how to generate list dynamically in angular.js

can you please tell me how to create list dynamically in angulat.js..Actullly I am able to make list when user press add button and fill the field .
In other words ,Please check this fiddle whenever you fill the fields it generate a row.And you can get Id when you click the row .Fiddle http://jsfiddle.net/wc4Jm/6/
Now I am trying to do this using bootstrap model .in other words on button click first I show a pop up screen then there is "add" button .on click that it generate the row.but I am getting "undefined".My I insert the model div inside the controller ? here is
http://jsbin.com/vubojoxo/4/
Why I am getting this error ?
XMLHttpRequest cannot load file:///C:/Users/asd/Desktop/angular/angularproject/dialog.html. Received an invalid response. Origin 'null' is therefore not allowed access.
I am getting this error when I used plunker..and run in my desktop ..
I make this html ?
<!doctype html>
<html ng-app="plunker">
<head>
<script src="angular.js"></script>
<script src="ui-bootstrap-tpls-0.2.0.js"></script>
<link href="bootstrap-combined.min.css" rel="stylesheet">
<script src="index.js"></script>
</head>
<body>
<div ng-controller="DialogDemoCtrl">
<a class="btn" data-toggle="modal" href="" ng-click="openPopupScreen()">Add Contend</a>
</div>
</body>
</html>
....
Dialog.html
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h1>Add Element</h1>
</div>
<div class="modal-body">
<form >
<label>Name:</label><input type="text" class="span3" ng-model="activeItem.name"></br>
<label>Content Name:</label><input type="password" class="span3" ng-model="activeItem.content"></br>
<button type="submit" class="btn btn-success" ng-click="addItem()">Add In List</button>
<button type="reset" class="btn ">Clear</button>
</form>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal" aria-hidden="true">close</a>
</div>
js code:
var myApp = angular.module('plunker', ['ui.bootstrap']);
myApp.controller('DialogDemoCtrl', function($scope,$dialog) {
$scope.items = [];
$scope.activeItem = {
id:'',
name: '',
content: ''
};
$scope.addItem = function () {
$scope.activeItem.id = $scope.items.length + 1;
$scope.items.push($scope.activeItem);
$scope.activeItem = {}; /* reset active item*/
};
$scope.getId = function (item) {
alert('ID: '+item.id);
};
$scope.openPopupScreen = function () {
alert('Check Open pop up screen');
$dialog.dialog({}).open('dialog.html');
};
});
Check this Plunker
In this example i used angular-ui library which wraps bootstrap's modal to angular
based on this StackOverflow Answer
ModalDemoCtrl
$scope.items = [];
$scope.getId = function(item) {
alert('ID: ' + item.id);
};
// This opens a Bootstrap modal
$scope.open = function() {
var modalInstance = $modal.open({
template: $scope.modal_html_template,
controller: ModalInstanceCtrl
});
modalInstance.result.then(function(newItem) {
// On modal success
newItem.id = $scope.items.length + 1;
$scope.items.push(newItem);
}, function() {
// On modal cancelation
});
}
ModalInstanceCtrl
$scope.name = '';
$scope.content = '';
$scope.ok = function() {
var response = {
'name': $scope.name,
'content': $scope.content
};
$modalInstance.close(response);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
HTML
<body>
<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">
<div class="form-group">
<label>Name</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.name" placeholder="Enter Name">
</div>
<div class="form-group">
<label>Content</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.content" placeholder="Enter Content">
</div>
</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>
<div class="container">
<h2>Modal Example https://stackoverflow.com/questions/24988561</h2>
<button class="btn" ng-click="open()">Open Modal</button>
<div>
<ul>
<li ng-repeat="item in items">
<a ng-click="getId(item)">{{ item.id }} | {{ item.name + ' ' + item.content }}</a>
</li>
</ul>
</div>
</div>
</div>
</body>

AngularJS toggle button

I am trying to create a toggle button in Angular. What I have so far is:
<div class="btn-group">
<a class="btn btn-primary pull-right"
ng-click="toggleArchive(true)"
ng-show="!patient.archived">Archive patient</a>
<a class="btn btn-danger pull-right"
ng-click="toggleArchive(false)"
ng-show="patient.archived">Unarchive patient</a>
.... some other buttons ....
</div>
Basically I achieve toggling, by having TWO buttons, and toggling between them. This is causing issues because the ng-hide just adds a display:none style to the button when it's hidden, which is causing me styling issues. Ideally I want to have ONE button, that has it's text, class and function call changed depending on the state of patient.archived.
What's a clean way to achieve this?
You should use ng-class to toggle between classes and bind the text with a regular Angular expression. Also, if your function toggleArchive only toggle the value, you can remove it and toggle the value from an Angular expression:
<a class="btn pull-right"
ng-class="{true: 'btn-primary', false: 'btn-danger'}[!patient.archived]"
ng-click="patient.archived = !patient.archived">
{{!patient.archived && 'Archive' || 'Unarchive'}} patient
</a>
for any other weary traveller...
you could simply have used ng-if. ng-if completely excludes the element from the DOM if false, so you'd have no issues with styles when not displayed. Also there is not really a need for the button group you could just change the text of the button
Something like this:
<button class="btn btn-primary pull-right"
ng-click="toggleArchive(true)"
ng-if="!patient.archived">Archive patient</button>
<button class="btn btn-danger pull-right"
ng-click="toggleArchive(false)"
ng-if="patient.archived">Unarchive patient</button>
It might help you:
<html>
<head>
<script src="js/angular.js"></script>
<script src="js/app.js"></script>
<link rel="stylesheet" href="css/bootstrap.css">
</head>
<body ng-app>
<div ng-controller="MyCtrl">
<button ng-click="toggle()">Toggle</button>
<p ng-show="visible">Hello World!</p>
</div>
</body>
</html>
function MyCtrl($scope) {
$scope.visible = true;
$scope.toggle = function() {
$scope.visible = !$scope.visible;
};
}
This may Help:
<!-- Include Bootstrap-->
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<!-- Code -->
Click here to <strong>Toggle (show/hide)</strong> description
<input type="checkbox" class="toggle-button"
ng-model="patient.archived">
Then style the checkbox like a button.
if the toggle needs to do more things, add the following to your patient class:
class Patient {
constructor() {
this.archived = false;
}
...
get angularArchived() {
return this.archived;
}
set angularArchived(value) {
if (value !== this.archived) {
toggleArchived(value);
}
this.archived = value;
}
}
then use
<input type="checkbox" class="toggle-button"
ng-model="patient.angularArchived">
This is the simplest answer I've found. I haven't tried it with animations because I just use it for quick setup.
<a ng-click="scopeVar=scopeVar!=true">toggle</a>
<div ng-show="scopeVar">show stuff</div>
with scopeVar=scopeVar!=true undefined becomes true.

Categories

Resources