Trigger on show event for bootstrap modal not working - javascript

This question has probably been answered already however I am trying to ask it as specific as possible.
Using the examples found here. Under the varying content based on trigger button.
I have a bootstrap modal that is opened with an <a></a> tag which needs to be given information from AngluarJS. The example uses Jquery to do some magic and pass the data in.
BIG Edit Lots of code appearing here because something is slightly wrong. I am thinking it is in when the scripts load.
On live demo please attempt to debug and find why the var Index = button.data('Index') comes out undefined. - Fixed - case sensitive
Final problem why is the jquery failing at
VM155:8 Uncaught TypeError: angular.element(...).scope(...).logic.UpdateNews is not a function
Done it works, I freaking got it all!
HTML:
<script src="http://www.jqueryscript.net/demo/Responsive-jQuery-News-Ticker-Plugin-with-Bootstrap-3-Bootstrap-News-Box/scripts/jquery.bootstrap.newsbox.min.js" type="text/javascript"></script>
<div class="row">
<div class="col-md-6 col-lg-3">
<div class="panel panel-default">
<div class="panel-heading"> <span class="glyphicon glyphicon-list-alt logo-inverse pull-left"></span><b> General News</b></div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12">
<ul class="demo1" style="overflow-y: hidden; height: 280px;" ng-model="Idk">
<li style="" class="news-item text-left" ng-repeat="item in News.GeneralNews"><strong>{{item.DateValue | date: "MMM dd yyyy"}}</strong>{{item.Preview}}<a class="FakeClickable" data-target="#GeneralModal" data-toggle="modal" data-Index="{{item.Index}}">Read more...</a></li>
</ul>
<div ng-if="Width>768">
<div ng-include="'../pages/Modals/General/GENERAL_INLINE.html?Update=Yes'"></div>
</div>
</div>
</div>
</div>
<div class="panel-footer"> </div>
</div>
</div>
Modal:
<div class="modal fade" id="GeneralModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="width:auto;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<div class="FixModalHeader">
<img style="vertical-align:middle" src="../Content/Images/Icons/favicon-32x32.png">
<span style="">{{NewsCast.HeaderTitle}}</span>
</div>
</div>
<div class="modal-body">
<div data-ng-include="'../pages/Modals/General/GENERAL_MODAL.html'"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
console.log("I was here!");
$('#GeneralModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var Index = button.data('Index') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
angular.element('#mycontroller').scope().logic.UpdateNews('General', Index);
angular.element('#mycontroller').scope().$apply();
})
});
</script>
<script>
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
What happens inside the last ng-include:
<div class="html-format">
<div ng-bind-html="NewsCast.General.Body">
</div>
What I need answered:
Can I have have the jquery function trigger and then change something in my AngularJs code? The way I have my modals set up is the text and stuff appearing on them is data-bound to Angular objects. If the jquery can change a value in my angular all my modals will work.
Even more specific if the jquery can call a function from my angularjs code and pass in some arguments I'll really be set.
I'll take suggestions on proper code edikit please

If I understand correctly then you can use a service for this. Inject the service into both the controller with the jquery and the controller with the databound DOMs. Then if you store the data as well as functions to alter the data in the service you can alter it in both places and also bind it to the $scope of each.
You can use a service for this as described above.
I'm not an expert on Angular code etiquette, but you can do it this way.
Services
Simpler example Note: see creating custom service.

Related

I want to load content into a bootstrap 4 modal using intercooler.js

I'm trying to load content into a modal using intercooler, example here:
http://jsfiddle.net/qvpy3coL/3/
I'm having no joy and wonder if this is possible, or whether the bootstrap js will conflict?
Html is:
<div id="confirm-me" class="btn btn-primary" data-toggle="modal"
data-target="#msgmodal" ic-get-from="/click" ic-target="dynamiccontent"
ic-trigger="click">
Click Me to show dynamic modal</div>
<div class="modal fade" id="msgmodal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">
Below will be dynamic content</h4>
</div>
<div id="dynamiccontent">
</div>
</div>
</div>
</div>
js is:
// mockjax stuff ...
$.mockjax({
url: "/click",
responseTime: 500,
response: function (settings) {
this.responseText = "Dynamic stuff here!";
}
});
I've never used intercooler but after a quick read it turns out there should be no problem.
The only requirement with dynamic content you want in the modal is that it should be valid HTML code.
I played with the example you put in some content:
$('#dynamiccontent').html('No, it wont have any problems as long as your placing HTML')
https://jsfiddle.net/5pe6yz0w/3/

Why doesn't my next modal.show() not always work?

I have two Bootstrap Modal's in my Template.PageName.helper Meteor.callPromise() that I would like to fire-up in a specific order. The order being: modal.hide('loadingPageAnimation') followed by modal.show('c2bNotifications').
By default, modal.hide('loadingPageAnimation') is activated in the page Router.route('/page') by modal.show('loadingPageAnimation')
This successfully displays the modal.show(loadingPageAnimation) while (in my helper) my Meteor.CallPromise() is awaiting results:
../client/main
Meteor.callPromise('c2b').then(
function(results) {
//### When results comes through, Modal.hide('loadingPageAnimation')
Modal.hide('loadingPageAnimation');
//### then Modal.show('c2bNotifications' along with results message)
Modal.show('c2bNotifications', {msg: results};
}).catch( function(error) {
alert("Error!");
}
);
The problem here is that, when the Meteor.callPromise('c2b') returns results, the Modal.hide('newLoadingModal'); is successfully hidden, but the Modal.show('c2bNotifications', {msg: results}); only shows sometimes and sometimes it does not show. I would like some consistency in Modal.show('c2bNotifications', {msg: results}); always showing/working. Can anyone explain why this happens and perhaps give a better coding solution whereby Modal.show('c2bNotifications', {msg: results}); is forced to show?
Find below my template file.
../client/main.html
<template name="c2bNotifications">
<div class="modal fade makeAnOffer">
<div class="modal-dialog modal-sm">
<div class="modal-content modal_MakeAnOffer">
<div class="modal-header">
<h4 class="modal-title">Notification </h4>
</div>
<div class="modal-body">
<div id = approvedMsg > {{msg}} </div>
</div>
<div class="modal-footer c2bNotifications">
<button type="button" class="btn btn-primary btn-lg" id="paymentNotificationClose" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</template>
Looking forward to your help
First solution: What you can do is to add a little timeout to let the first modal the time to be hidden. Then call the Modal.show().
{
Modal.hide('loadingPageAnimation');
setTimeout(function(){
Modal.show('c2bNotifications');
}, 1000);
}
The problem is that you need to wait for the first modal to hide because there is no parameter to add a callback to the Modal.hide() function with the peppelg:bootstrap-3-modal package. If the code above really doesn't work, you can add this code
Modal.allowMultiple = true;
Second solution: I see you that you are using the first modal to show a loading sign, maybe you could add this sign into the c2bNotifications, and showing it with an helper like that :
<template name="c2bNotifications">
<div class="modal fade makeAnOffer">
<div class="modal-dialog modal-sm">
<div class="modal-content modal_MakeAnOffer">
<div class="modal-header">
<h4 class="modal-title">Notification </h4>
</div>
{{#if isLoaded}}
<div class="modal-body">
<div id = approvedMsg > {{msg}} </div>
</div>
<div class="modal-footer c2bNotifications">
<button type="button" class="btn btn-primary btn-lg" id="paymentNotificationClose" data-dismiss="modal">Close</button>
</div>
{{else}}
<!-- insert loading page animation -->
{{/if}}
</div>
</div>
</div>
</template>
And your helper code should look like that:
Template.c2bNotifications.helpers({
isLoaded(){
// return true if your Meteor.callPromise succeed, otherwise false
},
});
Third solution:
You could try to create a homemade callback, maybe by checking if the modal exist in the DOM.

Lazy Load Images Only After Bootstrap Modal has Opened

I found two similar answers here but both were unsuccessful for my situation (given my limited ability to translate them to my situation). I have a page with a lot of fairly large images and the default method of Bootstrap is to load all the modal images upon page load. The visible html renders fairly quickly (I have a spinner for that) but the additional load time for the hidden modals makes the page impractical. I want the page to load only the visible (non-modal) content to complete the page load (and clear the spinner) and then load each modal's content only when that modal is fired. I've tried every lazyload solution I could find but the images will not render in the modal (the 'data-src' placeholders render but not the 'src' images that are supposed to replace them). I only want to lazyload (or load on 'show.bs.modal') the large images of the modal, those within the 'modal-body' class. I hope this is clear enough.
Sample code:
/* Javascript placed in the head */
<script>
function lazyLoad(){
var $images = $('.lazy_load');
$images.each(function(){
var $img = $(this),
src = $img.attr('data-src');
$img
.on('load',imgLoaded($img[0]))
.attr('src',src);
});
};
$('.modal-body').on("show.bs.modal", function () {
lazyLoad();
};
</script>
/* HTML in the modal section */
<div class="portfolio-modal modal fade" id="portfolioModal1" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="galleryheader">
<img src="headerimage_1.png" height="77" width="1024">
</div>
<div class="close-modal" data-dismiss="modal">
<div class="lr">
<div class="rl">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div>
<div class="modal-body lazy_load">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="images/largeimage_1A.jpg" height="585" width="800"class="img-centered" alt=""/>
</div>
<div class="modal-body lazy_load">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="images/largeimage_1A.jpg" height="585" width="800"class="img-centered" alt=""/>
</div>
<div class="modal-body lazy_load">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="images/largeimage_1A.jpg" height="585" width="800"class="img-centered" alt=""/>
</div>
</div>
</div>
</div>
<div class="close-lower" data-dismiss="modal">
<IMG SRC="images/close.jpg" WIDTH="85" HEIGHT="32"></a>
</div>
</div>
</div>
</div>
Firstly, put the lazy_load class on the img element, not on the parent div. Secondly the jQuery you need is something like this:
$('.portfolio-modal').on("show.bs.modal", function () {
$('.lazy_load').each(function(){
var img = $(this);
img.attr('src', img.data('src'));
});
});
Notes:
Use the portfolio-modal class to identify the modal.
Use the jQuery data() method to get the image to lazily load.

$scope variable not updating in view

I have the following snippet of code,
<div ng-controller="GraphCtrl" ng-if="errorTracerouteResultsLength!=0">
<h5>Erroneous Traceroute Paths
<small>Sub-heading</small>
</h5>
<a href="#" ng-repeat="(key, val) in errorTracerouteResults" ng-click="loadTraceroutePath(val.metadata);">
S: {{val.source.ip}}
D: {{val.destination.ip}}
</a>
</div>
It works fine, loadTraceroutePath belongs to another controller,(lets call it X) but somehow ng-click works and console.log gets printed out with the correct metadata value.
However, in controller X, I have,
$scope.loadIndividualTraceroutePath = function (metadataKey) {
$scope.noOfResults = 1;
}
In the html, I have {{noOfResults}} all over the place. Some of it are able to display 1 while some can't. I have already attached the ng-controller directives and point to controller X, but {{noOfResults}} does not display.
How can I make {{noOfResults}} display in any section of the HTML?
Edit: I have added the HTML.
<div class="row">
<div class="col-lg-9">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-bar-chart-o fa-fw"></i> Visualisation
<div class="pull-right">
Layout
</div>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="container" ng-controller="X">
<!--This does not work-->
{{noOfResults}}
</div>
<div>
<div ng-controller="IndividualTraceroutePathGraphCtrl" id="individual_traceroute_path_graph"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
The ng click in the first part of this question is way below.
You have a extra ; at the end, also you are not using the object what you are passing as a parameter to the function, hence Change
From:
<a href="#" ng-repeat="(key, val) in errorTracerouteResults" ng-click="loadTraceroutePath(val.metadata);">
To:
<a href="#" ng-repeat="(key, val) in errorTracerouteResults" ng-click="loadTraceroutePath(val)">
Then,
$scope.loadIndividualTraceroutePath = function (metadataKey) {
$scope.noOfResults = 1;
}
EDIT
You don't need to mention so many controllers in the view, have one controller where the function is defined and remove the rest, here, Update like this,
<div class="container" >
<!--This does not work-->
{{noOfResults}}
</div>
<div>
<div id="individual_traceroute_path_graph"></div>
</div>
</div>

AngularJS - JQuery News Ticker - After moving news the javascript function doesn't get called

This is an awkward problem, which will be better explained by looking at the live demo. Basically I have a news box populated with ng-repeat using Angular. Then I am using a jquery plugin called news ticker which allows the news headlines to move around. The first time you land on the page the news items are in their proper spots and they call the function accordingly. After moving them up or down, they stop calling the function, set a breakpoint in the code and after moving the breakpoint is never hit.
Edit - After researching this further I have found that it is because the elements need to be compiled using $compile after they're re added. However following some examples I have not gotten this to work. I need a way of compiling after a move event with this plugin.
Live demo
Angular Script for with function that should be called.
$scope.UpdateNews = function (item,number) {
console.log(item + ' ' + number);
switch (item)
{
case 'General':
$scope.NewsCast.General.Body = $scope.News.GeneralNews[number].Text;
break;
}
};
What the HTML looks like with the news boxes
<script src="http://www.jqueryscript.net/demo/Responsive-jQuery-News-Ticker-Plugin-with-Bootstrap-3-Bootstrap-News-Box/scripts/jquery.bootstrap.newsbox.min.js" type="text/javascript"></script>
<div class="row">
<div class="col-md-6 col-lg-3">
<div class="panel panel-default">
<div class="panel-heading"> <span class="glyphicon glyphicon-list-alt logo-inverse pull-left"></span><b> General News</b></div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12">
<ul class="demo1" style="overflow-y: hidden; height: 280px;" ng-model="Idk">
<li style="" class="news-item text-left" ng-repeat="item in News.GeneralNews"><strong>{{item.DateValue | date: "MMM dd yyyy"}}</strong> {{item.Preview}}<a class="FakeClickable" ng-click="UpdateNews('General',item.index)" data-target="#GeneralModal" data-toggle="modal">Read more...</a></li>
</ul>
<div ng-if="Width>768">
<div ng-include="'../pages/Modals/General/GENERAL_INLINE.html'"></div>
</div>
</div>
</div>
</div>
<div class="panel-footer"> </div>
</div>
</div>

Categories