I'm trying to insert url for menu through mustache template. But just the first value is being returned for the array.
Or is this the return method wrong
var main_menu_link = ["main_dashboard.html", "#", "online_dashboard.html","index.html","#","#","#"];
var url = "";
var i;
var url_link="";
for(i = 0; i < main_menu_link.length; i++) {
url += main_menu_link[i];
return '' + text + '';
}
CodePen working here
The return statement has to be after the loop:
var main_menu_link = ["main_dashboard.html", "#", "online_dashboard.html","index.html","#","#","#"];
var url = "";
var i;
var url_link="";
for(i = 0; i < main_menu_link.length; i++) {
url += '' + text + '';
}
return url;
Correct template as below in-case it can be of use to someone else
var link_details = { "link_details" :[
{ main_menu: "Dashboard", main_menu_link: "dashboard.html" },
{ main_menu: "Analytics", main_menu_link: "#" },
{ main_menu: "System", main_menu_link: "system.html" }
]};
var template = "<ul>{{#link_details}}<li>{{main_menu}}</li>{{/link_details}}</ul>";
var html = Mustache.to_html(template, link_details);
document.write(html)
Related
I am opening multiple pages in an iframe (one by one) i.e. i want to do it synchronously. So in a for loop i want to set iframe src property to url1 then once this page is loaded move to url2 and so on..
<iframe id="iframeExportPDF" onload="test();"></iframe>
$('#<%=Button1.ClientID%>').click(function (e) {
e.preventDefault();
var registrarIds = ($('#<%=lblRegistrarIdsForChart.ClientID%>').text()).split(',');
for (var i = 0; i < registrarIds.length; i++) {
var link = window.location.href;
var urlBase = link.substring(0, link.lastIndexOf("/") + 1);
//alert(registrarIds[i].toString());
ganttPopup(urlBase + 'GPS/CompetencyAssessment/GanttChart.aspx?id=' + registrarIds[i].toString(), registrarIds[i]);
sleep(25000);
}
});
function ganttPopup(url, id) {
iframeExportPDF.src = url;
//window.open(url, "_blank", "ganttChartPopup_" + id.toString(), "width=1100,height=600,scrollbars=yes,resizable=yes");
}
P.S. Previously i was doing the same with opening multiple windows but since i have 1100 records, window.open would not be feasible.
I found my answer here
var urls = [], iCount;
$(function () {
$('#<%=Button1.ClientID%>').click(function (e) {
e.preventDefault();
var registrarIds = ($('#<%=lblRegistrarIdsForChart.ClientID%>').text()).split(',');
iCount = registrarIds.length;
for (var i = 0; i < registrarIds.length; i++) {
var link = window.location.href;
var urlBase = link.substring(0, link.lastIndexOf("/") + 1);
var url = urlBase + 'GPS/CompetencyAssessment/GanttChart.aspx?id=' + registrarIds[i].toString();
urls.push(url);
}
redirect_url();
});
function redirect_url() {
if (iCount >= 0) {
setTimeout(function () {
$('#iframeExportPDF').attr('src', urls[iCount]);
iCount--;
redirect_url();
}, 15000);
}
}
});
var app = angular.module('myngCsv', [ngcsv]);
app.controller('ngcsvCtrl', function($scope,$csv) {
$scope.csv ={
content: null;
header: true,
headerVisible: true,
separator: ',',
separatorVisible: true,
result: null,
encoding: 'ISO-8859-1',
encodingVisible: true,
accept: ".csv"
};
});
This is what tried.
indeed.
You can write a function to convert CSV to JSON and pass your CSV object to it. All you need to do is to save the first row of CSV as headers (You can identify them by comma) and you can identify new entry by newline character \n
Go through the function I have written below.
function csvToJSON(csv, callback) {
var lines = csv.split("\n");
var result = [];
var headers = lines[0].split(",");
for (var i = 1; i < lines.length - 1; i++) {
var obj = {};
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
if (callback && (typeof callback === 'function')) {
return callback(result);
}
return result;
}
You can try using Papaparse looks very easy and elegant to use
Create fileReader directive:
<input type="file" data-file-reader-directive="fileContent" accept=".csv" />
Directive to get csv data from the file:
app.directive('fileReaderDirective', function() {
return {
restrict: "A",
scope: {
fileReaderDirective: "=",
},
link: function(scope, element) {
$(element).on('change', function(changeEvent) {
var files = changeEvent.target.files;
if (files.length) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
scope.$apply(function() {
scope.fileReaderDirective = contents;
});
};
r.readAsText(files[0]);
}
});
}
};
});
Create a factory to convert csv data to json data
app.factory('readFileData', function() {
return {
processData: function(csv_data) {
var record = csv_data.split(/\r\n|\n/);
var headers = record[0].split(',');
var lines = [];
var json = {};
for (var i = 0; i < record.length; i++) {
var data = record[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}
for (var k = 0; k < lines.length; ++k){
json[k] = lines[k];
}
return json;
}
};
});
check out the working example : https://plnkr.co/edit/ml29G85knZpWWNdG8TeT?p=preview
referring to this plunker:
https://plnkr.co/edit/kBoDTXmm2XbxXjpDA4M9?p=preview
I am trying to create a directive that takes an array of json objects, syntax highlights them and its that syntax highlighted element in the page.
I have had mixed results with different watching methods, but what I cant figure out in this one is why the same id:1 is showing all the way down the list, why not id:1, id:2, id:2, id:3 etc.
angular.module("ngjsonview",[]).directive('ngjsoncollection',['$sce', function(){
'use strict';
return {
transclude: false
,restrict:'E'
,scope:{ d:'=',o:"=" }
,templateUrl: "./template.htm"
,controller:function($scope,$sce){
var fnPretty = function(objData){
if (typeof objData != 'string') { var strOut = JSON.stringify(objData, undefined, 2); }
strOut = strOut.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
return strOut.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) { cls = 'key';}
else { cls = 'string'; }
} else if (/true|false/.test(match)) { cls = 'boolean';}
else if (/null/.test(match)) {cls = 'null'; }
return '<span class="' + cls + '">' + match + '</span>';
});
};
$scope.html=$sce.trustAsHtml(fnPretty($scope.d));
$scope.$watchCollection('d',function(arrData){
$scope.arrHTML=[];
for (var i = 0, len = arrData.length; i < len; i++) {
$scope.arrHTML.unshift($sce.trustAsHtml(fnPretty(arrData[i])));
}
});
}
};
}]);
moving the timeout into a function helped with the specific problem I had
$scope.arrData=[];
function addIt(x) {
$timeout(function(){
$scope.arrData.push({id:x});
}, 100);
}
for(var i=0; i < 100; i++){
addIt(i)
}
I am using angular $timeout as,
$scope.alltexts = ["hii" , "hello" , "hehe"]
var sendtime = 60000
for (var i = 0; i < $scope.alltexts.length; i++) {
var text = $scope.alltexts[i]
$setTimeout(function() {}, (function(){$scope.addtext(text)}, sendtime + (i * 60000)));
};
$scope.addtext = function(text){
console.log(text)
}
But after each one minute it only console "hehe". Means it considers only last value. Please let me know how should I get proper results.
Too much of closures today, you are always passing the last index... a closure will create a new scope for each iteration.
$scope.alltexts = ["hii" , "hello" , "hehe"]
var sendtime = 60000
for (var i = 0; i < $scope.alltexts.length; i++) {
(function(i){
var text = $scope.alltexts[i]
$setTimeout(function() {}, (function(){$scope.addtext(text)}, sendtime + (i * 60000)));
})(i)
};
$scope.addtext = function(text){
console.log(text)
}
Try this
$scope.alltexts = ["hii" , "hello" , "hehe"]
var sendtime = 60000
for (var i = 0; i < $scope.alltexts.length; i++) {
(function(i){
var text = $scope.alltexts[i]
$setTimeout(function() {}, (function(){$scope.addtext(text)}, sendtime + (i * 60000)));
})(i)
};
$scope.addtext = function(text){
console.log(text)
}
I am trying to get innerHTML of a contenteditable div via function defined in controller of angularjs but it returns undefined every time.. what are the alternatives or how can I handle this issue?
$scope.genrate_HTML=function()
{
var read_string=document.getElementsByClassName("MainPage");
//console.log(read_string);
var p_tag= '\n<p id="test"> \n'+read_string.innerHTML+'\n </p>';
//document.getElementById("createdHTML").value = p_tag ;
//$compile( document.getElementById('createdHTML') )($scope);
}
the contenteditble div's classs name is "MainPage"
VisualEditor.controller("GenrateHTML",function($scope){
$scope.savefile=function()
{
$scope.genratedHTML_text=document.getElementById("createdHTML").value;
var text_file_blob= new Blob([$scope.genratedHTML_text],{type:'text/html'});
$scope.file_name_to_save=document.getElementById("file_name").value ;
var downloadLink=document.createElement("a");
downloadLink.download=$scope.file_name_to_save;
downloadLink.innerHTML="Download File";
if(window.URL!=null)
{
downloadLink.href=window.URL.createObjectURL(text_file_blob);
}
else
{
downloadLink.href = window.URL.createObjectURL(text_file_blob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
$scope.toggleModal = function(){
$scope.showModal = !$scope.showModal;
};
///add details
$scope.details=[];
$scope.addDetails=function(){
$scope.details.push({
Title:$scope.Details_Title,
meta_chars:$scope.Details_metaChars,
version:$scope.Details_version,
Auth_name:$scope.Details_AuthName,
copyRights:$scope.Details_copyRights
});
document.getElementById("createdHTML").innerHTML = $scope.details;
};
$scope.$watch('details', function (value) {
console.log(value);
}, true);
/////////////////////
$scope.genrate_HTML=function()
{
var read_string=document.getElementsByClassName("MainPage");
//console.log(read_string);
var p_tag = '';
for (var i = 0; i < read_string.length; i++) {
p_tag += '\n<p id="test_"' + i + '> \n' + read_string[i].innerHTML + '\n </p>';
document.getElementById("createdHTML").value = p_tag;
}
//$compile( document.getElementById('createdHTML') )($scope);
}
});
getElementsByClassName returns an Array, so, your read_string variable is an Array type. you should iterate through the elements of read_string with for loop.
NOTE: Please check the p element's id here aswell. Because id must be unique!
$scope.genrate_HTML = function() {
var read_string = document.getElementsByClassName("MainPage");
var p_tag = '';
for (var i = 0; i < read_string.length; i++) {
p_tag += '\n<p id="test_"'+i+'> \n'+read_string[i].innerHTML+'\n </p>';
}
/* Other code here... */
}
UPDATE: Don't use the code below! If read_string returns with no elements than your code will crash!
But if it's a 1 element Array then you can take the value like:
$scope.genrate_HTML = function() {
var read_string = document.getElementsByClassName("MainPage");
var p_tag= '\n<p id="test"> \n'+read_string[0].innerHTML+'\n </p>';
/* Other code here... */
}
I hope that helps. If it doesn't then paste the full code of the Controller.