Ui-tabset and bootstrap-daterangepicker not working together? - angular-bootstrap

I have an application where I am using ui-bootstrap-tabs. documentation here. With the ng-bs-daterangepicker.
The behavior I am observing is that whenever I put the daterangepicker inside the ui-tab. It is not able to catch the events attached to it.
But when I move that input tag outside the ui-tabs, it's able to catch the events associated with it.
I have created a working plunker to highlight my issue.
<body ng-app="myApp">
<div ng-controller="testController">
<uib-tabset>
<uib-tab index="0" heading="Drivers"></uib-tab>
<uib-tab index="1" heading="Charts">
<input class="btn btn-danger" type="daterange" id="daterange1" ng-model="dates" format="DD MMM" ranges="ranges" />
</uib-tab>
</uib-tabset>
<!-- <input class="btn btn-danger" type="daterange" id="daterange1" ng-model="dates" format="DD MMM" ranges="ranges" /> -->
</div>
</body>
Here there are two input tags. One inside the uib-tab and other outside it.
$scope.dates = {
startDate: moment().startOf('day'),
endDate: moment().endOf('day')
};
$scope.ranges = {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
'Last 7 days': [moment().subtract('days', 7), moment()],
'Last 30 days': [moment().subtract('days', 30), moment()],
'This month': [moment().startOf('month'), moment().endOf('month')]
};
$('#daterange1').on('apply.daterangepicker', function(ev, picker) {
console.log(picker.startDate);
console.log(picker.endDate);
});
The event apply.daterangepicker is not called when I activate the inside input button but is called when I activate the outside one.
My approach
I am guessing it's not a scope issue as highlighted in some posts. Because if it was that, then how come even the date is being populated.
Another thing could be the Known issue column which says
To use clickable elements within the tab, you have override the tab
template to use div elements instead of anchor elements, and replicate
the desired styles from Bootstrap's CSS. This is due to browsers
interpreting anchor elements as the target of any click event, which
triggers routing when certain elements such as buttons are nested
inside the anchor element.
maybe somehow this is stopping the event propagation. I am stuck at this point and can't think of a solution on how to fix it. Hoping the community would help here...

In case of $('#daterange1').on the object to which the event if getting attached must exist at the moment when .on() is invoked.
When daterangepicker is initialized inside Tabs component you could attach event like this:
$("body").on("apply.daterangepicker", "#daterange1", function(e,picker) {
console.log(picker.startDate);
console.log(picker.endDate);
});
Modified plunker

Related

Mixing Alpine.js with 'static' serverside markup, while getting the benefits of binding, etc

I'm new to Alpine and struggling to wrap my head around how to make a scenario like this work:
Let's say I have a serverside built page, that contains some buttons, that represent newsletters, the user can sign up to.
The user might have signed up to some, and we need to indicate that as well, by adding a css-class, .i.e is-signed-up.
The initial serverside markup could be something like this:
<button id='newsletter-1' class='newsletter-signup'>Newsletter 1</button>
<div>some content here...</div>
<button id='newsletter-2' class='newsletter-signup'>Newsletter 2</button>
<div>more content here...</div>
<button id='newsletter-3' class='newsletter-signup'>Newsletter 3</button>
<div>and here...</div>
<button id='newsletter-4' class='newsletter-signup'>Newsletter 4</button>
(When all has loaded, the <button>'s should later allow the user to subscribe or unsubscribe to a newsletter directly, by clicking on one of the buttons, which should toggle the is-signed-up css-class accordingly.)
Anyway, then I fetch some json from an endpoint, that could look like this:
{"newsletters":[
{"newsletter":"newsletter-1"},
{"newsletter":"newsletter-2"},
{"newsletter":"newsletter-4"}
]}
I guess it could look something like this also:
{"newsletters":["newsletter-1", "newsletter-2", "newsletter-4"]}
Or some other structure, but the situation would be, that the user have signed up to newsletter 1, 2 and 4, but not newsletter 3, and we don't know that, until we get the JSON from the endpoint.
(But maybe the first variation is easier to map to a model, I guess...)
Anyway, I would like to do three things:
Make Alpine get the relation between the model and the dom elements with the specific newsletter id (i.e. 'newsletter-2') - even if that exact id doesn't exist in the model.
If the user has signed up to a newsletter, add the is-signed-up css-class to the corresponding <button> to show its status to the user.
Bind to each newsletter-button, so all of them – not just the ones, the user has signed up to – listens for a 'click' and update the model accordingly.
I have a notion, that I might need to 'prepare' each newsletter-button beforehand with some Alpine-attributes, like 'x-model='newsletter-2', but I'm still unsure how to bind them together when Alpine has initialising, and I have the data from the endpoint,
How do I go about something like this?
Many thanks in advance! 😊
So our basic task here is to add/remove a specific item to/from a list on a button click. Here I defined two component: the newsletter component using Alpine.data() creates the data (subs array), provides the toggling method (toggle_subscription(which)) and the checking method (is_subscribed(which)) that we can use to set the correct CSS class to a button. It also handles the data fetching in the init() method that executes automatically after the component is initialized. I have also created a save method that we can use to send the subscription list back to the backend.
The second component, subButton with Alpine.bind() is just to make the HTML code more compact and readable. (We can put each attribute from this directly to the buttons.) So on click event it calls the toggle_subscription with the current newsletter's key as the argument to add/remove it. Additionally it binds the bg-red CSS class to the button if the current newsletter is in the list. For that we use the is_subscribed method defined in our main component.
.bg-red {
background-color: Tomato;
}
<script src="https://unpkg.com/alpinejs#3.x.x/dist/cdn.min.js" defer></script>
<div x-data="newsletter">
<button x-bind="subButton('newsletter-1')">Newsletter 1</button>
<button x-bind="subButton('newsletter-2')">Newsletter 2</button>
<button x-bind="subButton('newsletter-3')">Newsletter 3</button>
<button x-bind="subButton('newsletter-4')">Newsletter 4</button>
<div>
<button #click="save">Save</button>
</div>
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('newsletter', () => ({
subs: [],
init() {
// Fetch list of subscribed newsletters from backend
this.subs = ['newsletter-1', 'newsletter-2', 'newsletter-4']
},
toggle_subscription(which) {
if (this.subs.includes(which)) {
this.subs = this.subs.filter(item => item !== which)
}
else {
this.subs.push(which)
}
},
is_subscribed(which) {
return this.subs.includes(which)
},
save() {
// Send this.sub to the backend to save active state.
}
}))
Alpine.bind('subButton', (key) => ({
'#click'() {
this.toggle_subscription(key)
},
':class'() {
return this.is_subscribed(key) && 'bg-red'
}
}))
})
</script>

Scripts not working on partial view after Ajax call

I have called scripts on _Layout.cshtml page and my Index.cshtml page has partial view into it. So on page load, SignalR scripts working perfect on partial view, on page end I make another ajax request and load the partial view with another data filled in that and embed under already displayed data, and then the SignalR does not work on the newly embedded record.
This is my index page code:
<div class="col-md-6">
<div class="profile-body">
<div class="row infinite-scroll">
#Html.Partial("_AlbumRow", Model)
</div>
</div>
</div>
This is my partial View Code:
#model IEnumerable<SmartKids.Lib.Core.ViewModels.FileMediaAlbumsVM>
#foreach (var item in Model)
{
<div class="widget">
<div class="block rounded">
<img src="#Url.Content(item.ImageUrl)" alt="#item.Title">
<input type="button" data-image-id="#item.imageId" class="btn btn-sm btn-default">Like</input>
</div>
</div>
}
Kindly help me how to resolve this issue that after making an ajax request I am not able to get those SignalR working. Here is more to say when I put the SignalR scripts on PartialView that works but it also sucks that on each ajax request there is again SignalR loaded on the page and when I click on LIke button it makes many calls to the function behind it.
Kindly help me to resolve this issue, I am stuck at this point since 1 week.
Here is signalR Code:
$(".btn.btn-sm.btn-default").on("click", function () {
var imageId = $(this).attr("data-image-id");
albumClient.server.like(imageId);
});
Problem: You are binding event to elements directly, So when you remove this element and replace it with a different one the events are also removed along with that element, This is something like strongly coupled.
Solution: Use Jquery event delegation. This will make sure the events will be triggered on the current elements and also all the elements that can come in future.
syntax is as below.
$(document).on("click", ".btn.btn-sm.btn-default",function () {
var imageId = $(this).attr("data-image-id");
albumClient.server.like(iamgeId);
});
NOTE: This was never a singlaR issue, it was Jquery issue.
Efficient Way: The problem in using $(document).on("click"... is that when ever there is a click happening on the entire page the Jquery framework will bubble the events from the clicked element upwards(its parent, and its parent and so on..) unless the element specified in the selector arrives, So its kind of performance hit as we don't want this check's to run if we are clicking outside the required area ( button .btn.btn-sm.btn-default in this example).
So best practice is to bind this event delegation to the closest parent possible which will not be removed, <div class="row infinite-scroll"> in this question. So that only when the click happens within this element the event bubbling will happen and also will be stopped once it reaches the parent element,it acts kind of a boundary for event bubbling.
$('.row.infinite-scroll').on("click", ".btn.btn-sm.btn-default",function () {
var imageId = $(this).attr("data-image-id");
albumClient.server.like(iamgeId);
});

prototype : onclick remove previous element

i have html as below in which onclick of <a> i want to remove the text box above it.
<input class="sku-box" class="input-text validate-number" type="text" title="file-number" name="sku[]">
<a value="remove" onclick="remove()" href="javascript:void(0);">remove</a>
<input class="sku-box" class="input-text validate-number" type="text" title="file-number" name="sku[]">
<a value="remove" onclick="remove()" href="javascript:void(0);">remove</a>
my solution to this, i changed the <a> tag to this.
remove
and my prototype function look like this
function removefield(ele)
{
$(ele).previous().remove();
ele.remove();
}
You have several options for observing click events, and usually I wire up click events after the dom is loaded using something like:
document.on('click', 'a', myFunction.BindAsEventListener())
The above statement sets you up for observing all click events occurring for the a element firing up the function myFunction. Once you have this established you can then either trap the event or simply allow it to bubble up or do both, trap and bubble up the event.
However, with the direction you are going there you would be better off to pass the identity of your a tag to the remove function, then it is easy to remove the previous element. So you would have:
<a id="a_tag1" value="remove" onclick="remove('a_tag1')" href="javascript:void(0);">remove</a>
Then your function remove might look something like this:
function remove(a) {
// prev element
var elm = $(a).previous('input');
// remove it
if(elm)
elm.remove();
}
This is very basic and in reality you would need to do things to guarantee that the previous input element you are grabbing is associated with the a element you clicked. You could do this by agreeing on a new data-xxxx element tag or an arbitrary class name you can use to compare the elements. For example, your a tag might look like:
<a data-group='monkeys'>...</a>
And the cooresponding input tag might look like:
<input data-group='monkeys'>...</input>
Then, in the above code where you call previous on the a tag, you would construct your select to include a test on the data-group value that matches the current a tag.
Karl..

Angular Validation $parsers

When we have a controller or ng-model-controller we can do
ctrl.$parsers.push(function(viewValue){
ctrl.$setValidity('valid', true);
});
and in the end $digest is called automatically and validation renders.
What if I want to validate a field on blur. and I do
element.blur(function(){
[validations]
ctrl.$setValidity('valid', false);
})
and the result don't change on html with elements ng-binded, how to render this change?
You have to call ctrl.$setValidity('valid', false); within scope.$apply
scope.$apply(function(){
ctrl.$setValidity('valid', false);
})
Or better yet, in order to avoid problems further on, use CSS to solve this problem. Let's assume the following code:
<textarea ng-model="description" ng-minlength="50"></textarea>
<span class="error" ng-show="myform.$error.minlength">Too short!</span>
<span class="error" ng-show="myform.$error.someOtherValidation">Err!</span>
When you start typing, Angular starts validation, and errors appear (which is sometimes desirable, but more often, it's not).
What you can do in order not to mess up Angular's internals, is some CSS magic:
textarea:focus ~ .error {
display:none;
}
The tilde is a general sibling selector, so as long as you have your fields focused all your errors will stay hidden.

How to serialize a form with dynamically added inputs using jQuery?

I've read through a lot of questions addressing similar question but I can't get a grip on it, yet.
I have a simple HTML form just like
<form id="edit-items" name="edit-items" onsubmit="saveItems();">
<input type="submit" value="Save">
<input class="item" id="ei81" type="hidden" name="i[81]" value="1">
<input class="item" id="ei124" type="hidden" name="i[124]" value="1">
</form>
The two existing hidden inputs could be set upon document loading due to a prior save.
Now I have images (kind of a menu). If they are clicked a corresponding hidden input is appended to the form:
<img id="i37" class="clickable-item" src="items/i37.gif" title="item name" onclick="addItem(37,1)" />
The addItem function:
function addItem(id,n) {
var zitem = $("#e"+id);
if ( 0 in zitem ) {
if ( zitem.val() > 0 ) {
var newcnt = parseInt(zitem.val()) + n;
if ( newcnt <= 0 ) {
zitem.remove();
}
else {
zitem.val(newcnt);
}
}
}
else if(n == 1) {
var iform = $("#edit-items");
iform.append("<input class=\"item\" id=\"e"+id+"\" type=\"hidden\" name=\"i["+id+"]\" value=\"1\">");
}
}
This part all works correct, after clicking the image, my form looks like
<form id="edit-items" name="edit-items" onsubmit="saveItems();">
<input type="submit" value="Save">
<input class="item" id="ei81" type="hidden" name="i[81]" value="1">
<input class="item" id="ei124" type="hidden" name="i[124]" value="1">
<input class="item" id="ei37" type="hidden" name="i[37]" value="1">
</form>
which is exactly what I want. But then when hitting the submit button only the first two elements are submitted (the ones which have not been added dynamically).
Now, I read a lot about .bind and .live handlers but I am missing some point obviously. I tried to delete the onclick attribute on the images and to bind the .live to them since they are causing the new inputs:
$(".clickable-item").live("click", function() {
addItem($(this).attr("id"),1);
});
However, the ID is not transferred which is needed, though (hence no correct input is added). I learned that .live doesn't bind the handler to any elements but to the event.
Is it even possible to pass the element which has been clicked to the live handler?
Should the images even be watched by .live or should it be bound to something else?
The last thing I learned form another question here is that the inputs should be watched by .live, since they are dynamically added. But what kind of event I would attach? The inputs themselves are not clicked.
I would really appreciate any help as I am cracking my head and starting to get lost on that one.
Thanks in advance,
Paul
Regarding live() [docs]: this refers to the clicked element, so you can pass it to addItem with addItem(this, 1). This part of your code should work.
If you don't add or remove images dynamically then there is no reason to use live. You can just use click() [docs] (and yes, don't use onclick in the HTML).
But I see another problem:
The image id is i37. $(this).attr("id") will return this value.
In your addItem function you then take this value and perform string concatenation. The result will be $("#ii37") (note the two is).
The input element you create will have the id ii37 and not i37.
If you correct this to match it with the other elements like in your example (i.e. i37) , you will have problems because you have several elements with the same id (the input element and the image). If the image comes before the input field in the hierarchy, then $("#i37") will always select the image and you cannot call .val() on an image.
As I don't know what is the overall purpose of the code and what you want to do, I cannot give any suggestion how to improve this. Maybe it is enough to just change the prefix of the image and input field ids.
I learned that .live doesn't bind the handler to any elements but to the event.
That is not correct. .live() binds the event handler to the document root. Events, if not cancelled, bubble up the DOM tree, so they reach the root eventually. There, the event.target [docs] property is examined to determine the element that was clicked.

Resources