js code to get the dynamic generated div IDs - javascript

I am working on java and angularjs application.
I have a html page which iterates the object and display the values on page.
html code:
<div id="{{value.pageIndex}}" ng-repeat="(key, value) in employees" class="myDivClass">
<div>
<h1><font color="red"> {{value.pageHeader}}</font></h1>
</div>
<div>
<h1> {{value.pageIndex}}</h1>
</div>
<div>text from html page</div>
</div>
I should not enclose the above html code inside another div as it will fail my other scenario's in my application.
I want to export the above html content to the PDF when user click on a button, issue is when i'm trying to get the value from html page as shown in below js code, only first iterated data is exported where as i want the entire data to be exported to the PDF.
js code:
$scope.export = function() {
var pdf = new jsPDF('landscape');
source = $('.one1');
pdf.addHTML(source, 0, 0, {
pagesplit: true
},function(dispose){
pdf.save('test.pdf');
});
}
Please find the demo of the above scenario: https://plnkr.co/edit/6jNIu5c26ACeTPsfACX2?p=preview
Any suggestions on how to pass the dynamic generated ID's to the js code and export the entire html data to PDF? Is there any way to pass dynamic generated ID's to the js code and export the entire data to the PDF.
PS: I should not enclose the above html code inside another div as it will fail my other scenario's in my application.

Use the class myDivClass to fetch your data instead of using id attribute.
You can use jQuery .each() to fetch all the data.
Add append-source div to html
<body>
<div ng-controller="listController">
<button ng-click="export()">export</button>
<div id="{{value.pageIndex}}" ng-repeat="(key, value) in employees" class="myDivClass">
<div> <h1><font color="red"> {{value.pageHeader}}</font></h1> </div>
<div><h1> {{value.pageIndex}}</h1></div>
<div>text from html page</div>
</div>
</div>
<div id="append-source"></div>
</body>
Use this div to create pdf in JavaScript
$scope.export = function() {
var pdf = new jsPDF('landscape');
var source = $('#append-source');
$('.myDivClass').each(function(){
var html = $(this);
source.append(html);
});
console.log(source);
pdf.addHTML(
source, 0, 0, {
pagesplit: true
},
function(dispose){
pdf.save('test.pdf');
}
);
}

Related

HTML Button Appears as Text after $compile [duplicate]

This question already has answers here:
how can we use $compile outside a directive in Angularjs
(5 answers)
"Thinking in AngularJS" if I have a jQuery background? [closed]
(15 answers)
Closed 4 years ago.
I am trying to create a pop up dialog with two buttons created in JS code with angular. The following code that produces the buttons...
var html = $('<button ng-click = "cancelAlert()" > Cancel</button > <button ng-click="continueAlert()">Continue</button>');
var div = $compile(html);
var content = div($scope);
document.getElementById('dialogboxhead').innerHTML = "header";
document.getElementById('dialogboxbody').innerHTML = "body";
document.getElementById('dialogboxfoot').innerHTML = content;
Gives me the following html text instead of the actual buttons themselves...
[[object HTMLButtonElement], [object Text], [object HTMLButtonElement]]
Am I missing something here that I have forgotten to add in?
The HTML looks like the following...
<div id="dialogoverlay"></div>
<div id="dialogbox">
<div>
<div id="dialogboxhead"></div>
<div id="dialogboxbody"></div>
<div id="dialogboxfoot"></div>
</div>
</div>
The $compile method accepts a string argument if you want to provide markup in this way.
Avoid wrapping the input for $compile with anything (ie $(..)). Instead, just pass the html string directly to the $compile() method, and also attach the div via the DOM append() method, and you should find this will work as expected:
var html = '<button ng-click="cancelAlert()">Cancel</button><button ng-click="continueAlert()">Continue</button>';
var div = $compile(html);
...
document.getElementById('dialogboxfoot').append( div[0] );
For more infromation see the usage on the official docs.
Here's a link to a working jsFiddle
It is not wise to mix AngularJS and jQuery this way.
The major problem with this approach is that $compile adds watchers to the specified scope. Those watchers will remain after added elements are removed from the DOM. This will result in memory leaks. If this is a dialog box that is constantly being added and removed -- beware.
But if you must, don't use innerHTML to append compiled content:
̶d̶o̶c̶u̶m̶e̶n̶t̶.̶g̶e̶t̶E̶l̶e̶m̶e̶n̶t̶B̶y̶I̶d̶(̶'̶d̶i̶a̶l̶o̶g̶b̶o̶x̶f̶o̶o̶t̶'̶)̶.̶i̶n̶n̶e̶r̶H̶T̶M̶L̶ ̶=̶ ̶c̶o̶n̶t̶e̶n̶t̶;̶
var foot = document.getElementById('dialogboxfoot');
$(foot).append(content);
The DEMO
angular.module("app",[])
.controller("ctrl",function($scope, $compile) {
var html = $('<button ng-click = "cancelAlert()" > Cancel</button > <button ng-click="continueAlert()">Continue</button>');
var div = $compile(html);
var content = div($scope);
document.getElementById('dialogboxhead').innerHTML = "header";
document.getElementById('dialogboxbody').innerHTML = "body";
var foot = document.getElementById('dialogboxfoot');
$(foot).append(content);
})
<script src="//unpkg.com/jquery"></script>
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<div id="dialogoverlay"></div>
<div id="dialogbox">
<div id="dialogboxhead"></div>
<div id="dialogboxbody"></div>
<div id="dialogboxfoot"></div>
</div>
</body>

How to select elements from a handelbars template?

We have a div within our webpage:
<div id="person-details">
<div></div>
...
</div>
We select the relevant elements from this div using the following jQuery code:
var person = $("#person-details");
var children = release.find("div");
var fullname = children.first();
We use a render function to perform an ajax request to get a handlebars template that we're storing in an external file:
function _render() {
var templateScript;
template.getTemplate(filename).done(function(template) {
templateScript = Handlebars.compile(template);
fullname.html(templateScript(context));
});
}
The template looks like the following:
<div>
<div>
<p>{{name}}</p>
</div>
<div>
<p>{{value}}</p>
</div>
</div>
After the render function has been called, we want to select any of the elements from within the template. For example we have tried using:
fullname.children('div');
but as the content has been dynamically generated we aren't able to get the nodes from within the DOM.
Is it even possible to select elements from within a generated handlebars template like this?
Thanks to #DanielShillcock for highlighting render() being asynchronous. Here is a solution:
function _render() {
var templateScript;
template.getTemplate(filename).done(function(template) {
templateScript = Handlebars.compile(template);
selector.html(templateScript(attribute));
value = selector.find("div");
});
}

insert db values to a .js file laravel

i have a view,
<div class="square_box col-xs-7 text-right">
<span>Views Today</span>
<div class="number" id="myTargetElement1"></div>
</div>
so i want to pass some values from my database to this .js file the value 90 for instance i want to fetch it from the database
var demo = new CountUp("myTargetElement1", 12.52, 90, 0, 6, options);
demo.start();
please help me out cause am stuck trying to figure out how to use the php query script inside a js file found in the public folder
I would suggest to use the html tag attribute to store the values and then retrieve it in your JavaScript file.
HTML file:
<div class="square_box col-xs-7 text-right">
<span>Views Today</span>
<div class="number" data-value={{$value}} id="myTargetElement1"></div>
</div>
JS file:.
<script>
var value = $('#myTargetElement1').attr('data-value');
var demo = new CountUp("myTargetElement1", 12.52, value, 0, 6, options);
</script>
The easiest thing to do would probably be to use ajax to call a view and display that view inside of your html.
Here is a very crude example.
$.ajax({
url: "/path/to/your/view",
cache: false
})
.done(function( html ) {
$( "#myTargetElement1" ).append( html );
});
You've to use AJAX to fetch your data into your JS code and then use it.
Or you can simply fetch your result from db and pass it to your view.
$value = DB::table('your_table')->get();
return view('some_view', [ 'value' => $value ]);
Then simply just echo it out using {{ blade }} in your view file
<script>
var demo = new CountUp("myTargetElement1", 12.52, {{ $value }}, 0, 6, options);
</script>

How to display value of a ViewBag in my view with a JS function?

I want to display the data from a ViewBag in my View with Javascript. Here is my code.
View
<span id='test'></span>
Javascript
function myFunction()
{
$('#test').text('#ViewBag.Test');
}
When myFunction() is called I get the text #ViewBag.Test but not his value. How can I fix this ?
You need to place your JavaScript which takes the #ViewBag.Test value in a page which is interpreted by the Razor view engine. My guess is that this is currently not the case.
If you want to keep your javascript codebase separate from the view (which is entirely reasonable) you can use a global variable:
// in the view:
var testText = '#ViewBag.Test';
// in external js
function myFunction() {
$('#test').text(window.testText);
}
Alternatively, you can use a data-* attribute:
<span id='test' data-text="#ViewBag.Test"></span>
// in external js
function myFunction() {
$('#test').text(function() {
return $(this).data('text');
});
}
What you should be ideally doing is passing the data to the view with a view model. Have a property to store that value you want to pass. For example. Let's think about a page to show the customer details and you want to get the last name in your javascript variable.
Your GET action method
public ActionResult View(int id)
{
var vm=new CustomerViewModel();
vm.LastName="Scott"; // You may read this from any where(DAL/Session etc)
return View(vm);
}
and in your view which is strongly typed to your view model.
#model CustomerViewModel
<div>
Some Html content goes here
</div>
<script type="text/javascript">
var lastName="#Model.LastName";
//Now you can use lastName variable
</script>
EDIT : (As per the question edit) To show the content on some event (ex : some button click), Store the value somewhere initially and then read it as needed and set it wherever you want.
#model CustomerViewModel
<div>
<span id="content"></span>
#Html.HiddenFor(s=>s.LastName)
<input type="button" id="btnShow" value="Show content" />
</div>
<script type="text/javascript">
$(function(){
$("btnShow").click(function(e){
$("#content").html($("#LastName").val());
});
});
</script>
Firstly make sure your ViewBag.Test does got a value, then use a div tag instead of a span and add the following code:
<script type="text/javascript">
$(document).ready(function () {
StartRead();
});
function StartRead() {
document.getElementById("test").innerHTML = '#ViewBag.Test';
}
</script>

grails - returning Object or id from formRemote

I have a grails app where, after a user enters a name for a new domain object (Sync), I want to save the object, move to a fragment on the same page, and change the css class of a div (to js colorbox, if that matters).
To do this, I use an anchor to set the class and move to the fragment and use JS to submit a g:formRemote. However, the formRemote does not return the created object.
partial of gsp:
<g:formRemote url="[controller: 'Main', action:'createNewSync']" name="newSyncForm" >
<g:field type="text" name="newSyncName" />
<a id="ns-link" href="#outline_content" class="outline">
<script>
$('#ns-link').click(function(){
$('#newSyncForm').submit();
});
</script>
</g:formRemote>
Later in the gsp, we want to move to use the colorbox with the outline_content inside. Notice the syncInstance.name is needed.
<script>
$(document).ready(function(){
$(".outline").colorbox({inline:true, width:"1140px", escKey:false, overlayClose:false});
</script>
<div id="sync" class="hidden">
<div id='outline_content' style='padding:10px; background:#fff;' >
<h2 class="nameheader"><strong style="color:#000;">New Sync:</strong><span class="editable_textile">${syncInstance?.name}</span></h2>
<div class="number1"><img src="../images/1.png" border="0" /></div>
.....
controller:
def createNewSync(){
params.name = params.newSyncName
def syncInstance = Sync?.findByName(params.newSyncName)
if (!syncInstance)
{
syncInstance = new Sync(params)
def u = User.findByUsername(springSecurityService.principal)
syncInstance.properties['createdBy'] = u
syncInstance.properties['createdDate'] = new Date().toString()
syncInstance.properties['lastRunTime'] = "Never"
syncInstance.properties['lastRunOutcome'] = "---"
syncInstance.properties['isScheduled'] = false
syncInstance.properties['isComplete'] = false
syncInstance.save(failOnError: true, flush: true)
}
//doesn't send anything back to page if it's been called remotely
[syncInstance: syncInstance]
}
Is there any way to get a reference to the created object to be used later on the page using this method? If not, is there another way to accomplish this?
Ok, so here is what I would do
1) Create a template for the sync. It would be everything contained inside the div with the id of "sync", but not the div itself.
2) Update your formRemote tag to update that div <g:formRemote update="sync" ... />
3) Render the template in your controller render(template: "path/to/template", model:[syncInstance: syncInstance])

Categories