Concatenation javascript error -probably simple to fix - javascript

I'm trying to do the next thing:
getChatListMessageString: function(dateObject, userID, userName, userRole, messageID, messageText, channelID, ip) {
var rowClass = this.DOMbufferRowClass,
userClass = this.getRoleClass(userRole),
colon = ': ';
if(messageText.indexOf('/action') === 0 || messageText.indexOf('/me') === 0 || messageText.indexOf('/privaction') === 0) {
userClass += ' action';
colon = ' ';
}
if (messageText.indexOf('/privmsg') === 0 || messageText.indexOf('/privmsgto') === 0 || messageText.indexOf('/privaction') === 0) {
rowClass += ' private';
}
var dateTime = this.settings['dateFormat'] ? '<span class="dateTime">'
+ this.formatDate(this.settings['dateFormat'], dateObject) + '</span> ' : '';
return '<div id="'
+ this.getMessageDocumentID(messageID)
+ '" class="'
+ rowClass
+ '">'
+ this.getDeletionLink(messageID, userID, userRole, channelID)
+ dateTime
//start of the code i added
+ '<a href="http://hostname.x/report_chat.php?usernameR='
+ userName
+ '/&useridR='
+ userID
+ '">'
+ '<img src="img/excl.png"></img></a>'
// end of the code i added
+ '<a href="http://www.hostname.x/'
+ userID
+ '" target="_blank"'
+ this.getChatListUserNameTitle(userID, userName, userRole, ip)
+ ' dir="'
+ this.baseDirection
+ '" onclick="ajaxChat.insertText(this.firstChild.nodeValue);">'
+ userName
+ '</a>'
+ colon
+ this.replaceText(messageText)
+ '</div>';
},
If I remove the portion that I added , the page works just fine. When I add it back , I get an Aw Snap error(cache reloaded -> incognito mode )
I'm pretty new with javascript so I can't really tell what I did wrong.
Thank you!
EDIT: THE AW SNAP ERROR comes from the <img> tag for whatever reason.

//Here a simple test
var Obj = (function(){
return{
DOMbufferRowClass : 'DOMbufferRowClass',
getRoleClass : function()
{
return 'roleClass';
},
settings : '',
getMessageDocumentID : function(){
return '123';
},
getDeletionLink : function(messageID, userID, userRole, channelID)
{
return 'DeletiongLink'
},
replaceText : function()
{
},
getChatListMessageString : function(dateObject, userID, userName, userRole, messageID, messageText, channelID, ip) {
var rowClass = this.DOMbufferRowClass,
userClass = this.getRoleClass(userRole),
colon = ': ';
if(messageText.indexOf('/action') === 0 || messageText.indexOf('/me') === 0 || messageText.indexOf('/privaction') === 0) {
userClass += ' action';
colon = ' ';
}
if (messageText.indexOf('/privmsg') === 0 || messageText.indexOf('/privmsgto') === 0 || messageText.indexOf('/privaction') === 0) {
rowClass += ' private';
}
var dateTime = this.settings['dateFormat'] ? '<span class="dateTime">'
+ this.formatDate(this.settings['dateFormat'], dateObject) + '</span> ' : '';
return `<div id="${this.getMessageDocumentID(messageID)}" class="${rowClass}">
${this.getDeletionLink(messageID, userID, userRole, channelID)} ${dateTime}
<a href="http://hostname.x/report_chat.php?usernameR='${userName}/&useridR=${userID}">
<img src="img/excl.png"/></a><a href="http://www.hostname.x/${userID} target="_blank"
this.getChatListUserNameTitle(userID, userName, userRole, ip) dir="{this.baseDirection}
onclick="ajaxChat.insertText(this.firstChild.nodeValue);">${userName}</a>${colon}${this.replaceText(messageText)}</div>`;
}
};
})();
console.log(Obj.getChatListMessageString("05102017", '1234',"admin", '456', 'Test','11', '127.0.0.1'));
I would simplify your code with template literals and avoiding all the concatenation mess.
getChatListMessageString : function(dateObject, userID, userName, userRole, messageID, messageText, channelID, ip) {
var rowClass = this.DOMbufferRowClass,
userClass = this.getRoleClass(userRole),
colon = ': ';
if(messageText.indexOf('/action') === 0 || messageText.indexOf('/me') === 0 || messageText.indexOf('/privaction') === 0) {
userClass += ' action';
colon = ' ';
}
if (messageText.indexOf('/privmsg') === 0 || messageText.indexOf('/privmsgto') === 0 || messageText.indexOf('/privaction') === 0) {
rowClass += ' private';
}
var dateTime = this.settings['dateFormat'] ? '<span class="dateTime">'
+ this.formatDate(this.settings['dateFormat'], dateObject) + '</span> ' : '';
return `<div id="${this.getMessageDocumentID(messageID)}" class="${rowClass}">
${this.getDeletionLink(messageID, userID, userRole, channelID)} ${dateTime}
<a href="http://hostname.x/report_chat.php?usernameR='${userName}/&useridR=${userID}">
<img src="img/excl.png"/></a><a href="http://www.hostname.x/${userID} target="_blank"
this.getChatListUserNameTitle(userID, userName, userRole, ip) dir="{this.baseDirection}
onclick="ajaxChat.insertText(this.firstChild.nodeValue);">${userName}</a>${colon}${this.replaceText(messageText)}</div>`;
}

Ouch! The best approach is not to build your HTML elements in this manner in the first place and use the DOM to construct and inject them into your document.
This makes the code MUCH easier to read and modify and removes the concatenation issue entirely.
Now, if you have errors, you can focus on the values your are assigning to the properties and not the syntax of the HTML.
// Create the div element in memeory
var div = document.createElement("div");
// Configure the attributes of that div
div.id = this.getMessageDocumentID(messageID);
div.classList.add(rowClass);
// Now, begin populating the div
div.innerHTML = this.getDeletionLink(messageID, userID, userRole, channelID) + dateTime;
// A new element belongs inside the div. Repeat the process:
var a1 = document.createElement(a);
a1.href = "http://hostname.x/report_chat.php?usernameR=" + userName + "/&useridR=" + userID;
var img = document.createElement("img");
img.src = "img/excl.png";
// Place the image into the anchor
a1.appendChild(img);
// Place the anchor into the div
div.appendChild(a1);
// Another anchor is now needed
var a2 = document.createElement(a);
a2.href = "http://www.hostname.x/" + userID;
a2.target = "_blank";
// It is unclear what the following line is based on the fact that whatever it returns, you have that
// being inserted where attributes go. It is commented here for that reason.
//this.getChatListUserNameTitle(userID, userName, userRole, ip) + " dir='" + this.baseDirection;
// Set up event handler for the anchor
a2.addEventListener("click", function(){
ajaxChat.insertText(this.firstChild.nodeValue);
});
// Populate the anchor
a2.innerHTML = userName;
// Insert this anchor into the div
div.appendChild(a2);
// Insert the final contents into the div
div.innerHTML += colon + this.replaceText(messageText);
// Return the final construct
return div;

Related

Order in jQuery calls

I have a jQuery loop that iterates over specifics elements of an HTML page. For every element, I do a switch over a variable and append HTML code in specific places.
The problem is that, one of those appends is an import to another Javascript file. This file uses a variable from the first one but, for some reason, that variable doesn't always have the correct value, depending on the order of the HTML elements in the page.
UPDATE
As requested, I created a Plunker so it's easy to see code:
http://plnkr.co/edit/mrEhgbZhhvu0Z4iniXGl?p=preview
Note: For this to work, you need to have correct pageId and appId for Instagram.
I'll put the code to be more clear:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<link rel="stylesheet" href="estilo.css">
</head>
<body>
<section id="rrss">
<!-- If I put this article block as the last one, it works -->
<article id="instagram">
<div data-rrss="instagram"></div>
</article>
<br/>
<article id="facebook">
<div data-rrss="facebook"></div>
</article>
<br/>
<article id="twitter">
<div data-rrss="twitter"></div>
</article>
</section>
<!-- SCRIPTS -->
<script src='scripts/data.js'></script>
<script src='scripts/jquery.js'></script>
<script>var customJquery = $.noConflict(true);</script>
<script src='../magic.js'></script>
</body>
</html>
data.js
var data = {
"facebook": {
"id": "facebook",
"width": 0,
"height": 0,
"custom_style": "border:none;overflow:hidden",
"hide_cover": false,
"show_facepile": true,
"small_header": false,
"adapt_container_width": true
},
"twitter": {
"id": "twitter",
"width": 0,
"height": 0,
"chrome": "nofooter noscrollbar noheader", // noborders transparent
"tweet_limit": 0,
"lang": "es",
"theme": "dark",
"link_color": "#0084b4"
},
"instagram": {
"id": "123456798123467/9876543219876543",
"hidecaption": false,
"custom_style": "overflow:auto;",
"max_width": 0,
"max_height": 500
},
"defaults": {
"width": 380,
"height": 500
}
}
magic.js
var rrss = customJquery('div[data-rrss]');
var conf = undefined;
var defaults = undefined;
var node = document.querySelectorAll('[data-rrss="instagram"]')[0];
customJquery.each(rrss, function(ix, it) {
var html = '';
var network = customJquery(it).data('rrss');
if (network === undefined || network == null || network.length <= 0)
return;
conf = data[network];
if (conf === undefined ||conf === null || conf.length <= 0)
return;
defaults = data['defaults'];
//Comprobamos si existe el key y si el value tiene texto
if(conf.id === undefined || conf.id === null || conf.id.length === 0)
return;
switch(network) {
case 'facebook':
html = '<iframe id="iFB" src="https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2F' + conf.id +
'&tabs=timeline' +
'&width=' + (conf.width <= 0 ? defaults.width : conf.width) +
'&height=' + (conf.height <= 0 ? defaults.height : conf.height) +
'&small_header=' + conf.small_header +
'&adapt_container_width=' + conf.adapt_container_width +
'&hide_cover=' + conf.hide_cover +
'&show_facepile=' + conf.show_facepile + '"' +
'width="' + (conf.width <= 0 ? defaults.width : conf.width) + '" ' +
'height="' + (conf.height <= 0 ? defaults.height : conf.height) + '" ' +
'style="' + conf.custom_style + '" ' +
'scrolling="no" frameborder="0" allowTransparency="true" allow="encrypted-media"></iframe>\n' +
'<script type="text/javascript">\n' +
' setInterval(() => {\n' +
' customJquery("#iFB")[0].src = customJquery("#iFB")[0].src\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
break;
case 'twitter':
html = '<a class="twitter-timeline" '+
'href="https://twitter.com/' + conf.id + '" ' +
'data-width="' + (conf.width <= 0 ? defaults.width : conf.width) + '" ' +
'data-height="' + (conf.height <= 0 ? defaults.height : conf.height) + '" ';
if (conf.chrome !== undefined && conf.chrome !== '') {
html += 'data-chrome="' + conf.chrome + '" ';
}
if (conf.tweet_limit > 0) {
html += 'data-tweet-limit="' + conf.tweet_limit + '" ';
}
html += 'data-lang="' + conf.lang + '" ' +
'data-theme="' + conf.theme + '" ' +
'data-link-color="' + conf.link_color + '"' +
'>Tweets by ' + conf.id + '</a>\n' +
'<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>';
break;
case 'instagram':
node = node.parentElement;
html = '<script async src="https://connect.facebook.net/es_ES/sdk.js"></script>\n' +
'<script src="../insta.js"></script>\n' +
'<script async defer src="https://www.instagram.com/embed.js"></script>\n' +
'<script>\n'+
' setInterval(() => {\n' +
' if (document.readyState === "complete") {\n' +
' window.instgrm.Embeds.process();\n' +
' }\n' +
' }, 100);\n' +
' setInterval(() => {\n' +
' fbAsyncInit();\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
break;
default:
html = '';
}
if (html != '') {
customJquery(it).replaceWith(html);
}
});
insta.js
window.fbAsyncInit = function () {
var html = '';
var style = '';
// When the Instagram's article bloke in HTML isn't the last one, this shows data from Twitter bloke
console.log(conf);
if (node !== undefined) {
if (document.getElementById('instagram') !== null) {
document.getElementById('instagram').innerHTML = '';
}
if (conf !== undefined && conf !== '') {
if (conf.max_width !== undefined && conf.max_width > 0) {
style += 'max-width: ' + conf.max_width + 'px;';
} else {
style += 'max-width: ' + defaults.width + 'px;';
}
if (conf.max_height !== undefined && conf.max_height > 0) {
style += 'max-height: ' + conf.max_height + 'px;';
} else {
style += 'max-height: ' + defaults.height + 'px;';
}
style += conf.custom_style;
}
var div = document.createElement('div');
div.id = 'instagram';
if (style !== '') {
div.style = style;
}
node.appendChild(div);
}
var pageId = conf.id.substring(0, conf.id.indexOf('/'));
var appId = conf.id.substring(conf.id.indexOf('/') + 1);
FB.init({
appId: appId,
autoLogAppEvents: true,
xfbml: true,
version: "v3.1"
});
FB.getLoginStatus(function (response) {
if (response.status === "connected") {
FB.api(
"/" + pageId + "/",
"GET", { "fields": "instagram_business_account" },
function (response) {
if (response.error && response.error !== '') {
console.log("Error recovering 'instagram_business_account': " + response.error.message);
} else {
FB.api(
"/" + response.instagram_business_account.id + "/media",
"GET", { "fields": "shortcode" },
function (response) {
for (var i = 0; i < response.data.length; i++) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
html = JSON.parse(this.response).html;
document.getElementById("instagram").innerHTML += html;
}
};
xhttp.open("GET", "https://api.instagram.com/oembed/?url=http://instagr.am/p/" + response.data[i].shortcode + "&omitscript=true&hidecaption=" + conf.hidecaption, true);
xhttp.send();
}
}
);
}
}
);
} else {
console.log("Error recovering access token: Not connected.")
console.log(response)
}
});
};
Well, I've solved with some ugly lonely line:
case 'instagram':
node = node.parentElement;
instaconf = conf; // ***** Saved the conf here *****
html = '<script async src="https://connect.facebook.net/es_ES/sdk.js"></script>\n' +
'<script src="../tecInsta.js"></script>\n' +
'<script async defer src="https://www.instagram.com/embed.js"></script>\n' +
'<script>\n'+
' setInterval(() => {\n' +
' if (document.readyState === "complete") {\n' +
' window.instgrm.Embeds.process();\n' +
' }\n' +
' }, 100);\n' +
' setInterval(() => {\n' +
' fbAsyncInit();\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
break;
Then changed the conf references to instaconf in insta.js file.
Since this file was loaded after the jQuery loops ended, the configuration was the last one in that loop (the last article in index.html file).
Here the problem is you are appending HTML elements dynamically. Here jquery will append in DOM then browser will some time to parse. Until that controller wont wait for the operation so loop continue execution. so here config is hold last element of twitter configuration.
And we can't pass reference to html string as per my knowledge. This we can achieve by passing config as string into html string from there we can pass to fbAsyncInit() method.
'<script>\n'+
' setInterval(() => {\n' +
' if (document.readyState === "complete") {\n' +
' window.instgrm.Embeds.process();\n' +
' }\n' +
' }, 100);\n' +
' setInterval(() => {\n' +
' let configuration = '+ JSON.stringify(conf) +';'+
' fbAsyncInit(configuration);\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
and we can receive as
window.fbAsyncInit = function (con) {
or we can pass call back function to html method and we do operation which is done in magic.js
Reference: http://api.jquery.com/html/#html-function
then we can return html accordingly.
I hope this will help you.

Error unexpected token }, Unexpected identifier

When i click click_profile_list i get error
or Uncaught SyntaxError: Unexpected identifier
function click_profile_list(choice, profileid, i_array) {
if(choice==0) {
alert("Profile", i_array.firstname);
}
else {
alert("Profile 2" , i_array.firstname);
}
}
for(var key in msg.db) {
var bypass = {
firstname: msg.db[key].firstname,
lastname: msg.db[key].lastname,
email: msg.db[key].user_email,
};
//html = '<div class="rows" onclick=click_profile_list(' + input + ',' + msg.db[key].id + ',' + bypass + ');>' ;
html = '<div class="rows" onclick="click_profile_list(' + input + ',' + msg.db[key].id + ',' + bypass + ');">' ;
html += msg.db[key].id + ' - ';
html += msg.db[key].firstname + ' - ';
html += msg.db[key].lastname + ' - ';
html += msg.db[key].fallback;
html += '</div>' ;
$('#show_list_window_body').append(html);
}
EDIT: , is removed, onclick="function();" added
$('#show_list_window_body').html(html);
for(var key in msg.db) {
var bypass = {
firstname: msg.db[key].firstname,
lastname: msg.db[key].lastname,
email: msg.db[key].user_email
};
var tmp_id = 'iDontKnow' + msg.db[key].id;
html = '<div class="rows" id="' + tmp_id + '">' ;
html += msg.db[key].id + ' - ';
html += msg.db[key].firstname + ' - ';
html += msg.db[key].lastname;
html += '</div>' ;
$('#show_list_window_body').append(html);
let $elem = $("<div class='rows' id='" + tmp_id + "'>");
$elem.click( () => click_profile_list(input, msg.db[key].id, bypass) );
}
Remove the extra comma at the end of your object :
var bypass = {
firstname: msg.db[key].firstname,
lastname: msg.db[key].lastname,
email: msg.db[key].user_email, // <-- Remove this comma
};
Then, add double quotes around your onclick function :
html = '<div class="rows" onclick="click_profile_list(' + input + ',' + msg.db[key].id + ',' + bypass + ');">'
Or (much) better, attach a click handler instead of inline javascript :
let $elem = $("<div class='rows'>")
$elem.click( () => click_profile_list(input, msg.db[key].id, bypass) )
let $clickme = $("<div>Click me!</div>")
$clickme.click(() => alert("it works!"))
$("#main").append($clickme)
#main * {
font-size: x-large;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main"></div>
Here's a proper jQuery solution:
const msg = {};
msg.db = {
alice: {
firstname: "Alice",
lastname: "Bob",
user_email: "alice#bob.com",
id: 1,
fallback: "fallback"
},
charlie: {
firstname: "Charlie",
lastname: "Delta",
user_email: "charlie#delta.com",
id: 2,
fallback: "fallback2"
}
};
function click_profile_list(e) {
$el = $(e.target);
var choice = 0; // get from whatever sets this
var user = msg.db[$el.data("key")];
if (choice == 0) {
alert(user.firstname);
}
}
var input = 0;
for (var key in msg.db) {
var user = msg.db[key];
$user = $("<div>").addClass("rows").data("key", key);
$user.text([user.id, user.firstname, user.lastname, user.fallback].join(" - "));
$('#show_list_window_body').append($user);
}
$('#show_list_window_body').on("click", ".rows", click_profile_list);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show_list_window_body"></div>
The list doesn't get awkward inline onclick code that tries to pass an object; instead each list item gets a data-key attribute referencing the database key. When clicked, the key is read back; this is used to grab the relevant data from the db.
You have two syntactical mistakes. One in your JavaScript and one in the HTML markup you produce.
JS
var bypass = {
firstname: msg.db[key].firstname,
lastname: msg.db[key].lastname,
email: msg.db[key].user_email, // <--- here is your issue, you should not use a comma after the last object element
};
HTML
html = '<div class="rows" onclick=click_profile_list(' + input + ',' + msg.db[key].id + ',' + bypass + ');>' ;
You must wrap the value of the attribute onclick with single or double quotes. In your code, just wrap it with double quotes onclick="...;"
Look #Jeremy Thille's answer for a better way to do this.

Define a scope in directive and use it in a view

I am using angular-treeview directive. Here , It is taking some time to load the tree, so I want to show a spinner for that time. So, I want to define a variable in directive and that will be used in the view so that I can show a spinner.
**angular-treeview.js**
(function ( angular ) {
'use strict';
angular.module( 'angularTreeview', [] ).directive( 'treeModel', ['$compile', function( $compile) {
return {
restrict: 'A',
link: function ( scope, element, attrs ) {
//tree id
var treeId = attrs.treeId;
//tree model
var treeModel = attrs.treeModel;
//node id
var nodeId = attrs.nodeId || 'id';
//node label
var nodeLabel = attrs.nodeLabel || 'label';
//node class
var nodeClass = attrs.nodeClass || 'type';
//children
var nodeChildren = attrs.nodeChildren || 'children';
//search by label
var searchQuery = attrs.searchQuery || '';
//function for highlighting search text
var searchHighlightFunction = attrs.searchHighlightFunction ||
function (content, text) {
return content
};
//css class to be added for highlighting
var searchHighlightClassName = attrs.searchHighlightClassName || '';
//filter to be used with search query
var searchFilter = attrs.searchFilter || '';
//tree template
var template =
'<ul>' +
'<li data-ng-repeat="node in ' + treeModel + '| ' + searchFilter + ':' + searchQuery + '" data-ng-init="node.collapsed=true">' +
'<i class="collapsed {{node.' + nodeClass + '}}" data-ng-show="node.' + nodeChildren + '.length && node.collapsed" data-ng-click="' + treeId + '.selectNodeHead(node)"></i>' +
'<i class="expanded {{node.' + nodeClass + '}}" data-ng-show="node.' + nodeChildren + '.length && !node.collapsed" data-ng-click="' + treeId + '.selectNodeHead(node)"></i>' +
'<i class="normal {{node.' + nodeClass + '}}" data-ng-hide="node.' + nodeChildren + '.length"></i> ' +
'<span data-ng-class="node.selected" data-ng-click="' + treeId + '.selectNodeLabel(node)" ' +
'ng-bind-html="' + searchHighlightFunction + '(node.' + nodeLabel + ', ' + searchQuery + ', \'' + searchHighlightClassName + '\', true)"></span>' +
'<div data-ng-hide="node.collapsed" data-tree-id="' + treeId + '" data-tree-model="node.' + nodeChildren +
'" data-node-id=' + nodeId + ' data-node-label=' + nodeLabel + ' data-node-children="' + nodeChildren + '"' +
' data-node-class="' + nodeClass + '" data-search-query="' + searchQuery + '" data-search-highlight-function="' + searchHighlightFunction + '"' +
' data-search-highlight-class-name="' + searchHighlightClassName + '" data-search-filter="' + searchFilter + '"></div>' +
'</li>' +
'</ul>';
//check tree id, tree model
if( treeId && treeModel ) {
/*
* to expand or collapse nodes on search text changes
*/
scope.$watch(searchQuery, function (newVal, oldVal) {
var node = scope.node;
if (newVal) {
if (newVal.length > 0) {
if (node) {
if ((node[nodeChildren] && node[nodeChildren].length)
|| (node[nodeChildren] && node[nodeChildren].length)) {
node.collapsed = false;
}
}
}
} else {
if (node && ((node[nodeChildren] && node[nodeChildren].length)
|| (node[nodeChildren] && node[nodeChildren].length))) {
node.collapsed = (scope[treeId].expandedNodes.indexOf(node[nodeLabel]) < 0);
}
}
});
//root node
if( attrs.angularTreeview ) {
//create tree object if not exists
scope[treeId] = scope[treeId] || {};
//this is where we are storing nodes by user to distinguish between
// those expanded by user from those done for showing search results
scope[treeId].expandedNodes = [];
scope.$watch(treeModel, function(newVal, oldVal) {
if (newVal) {
scope[treeId].expandedNodes = [];
}
});
//if node head clicks,
scope[treeId].selectNodeHead = scope[treeId].selectNodeHead || function( selectedNode ){
var expandedNodesIndex;
//Collapse or Expand
selectedNode.collapsed = !selectedNode.collapsed;
expandedNodesIndex = scope[treeId].expandedNodes.indexOf(selectedNode[nodeLabel]);
if (expandedNodesIndex > -1) {
if (selectedNode.collapsed) {
scope[treeId].expandedNodes.splice(expandedNodesIndex, 1);
}
} else {
if (!selectedNode.collapsed) {
scope[treeId].expandedNodes.push(selectedNode[nodeLabel]);
}
}
};
//if node label clicks,
scope[treeId].selectNodeLabel = scope[treeId].selectNodeLabel || function( selectedNode ){
//remove highlight from previous node
if( scope[treeId].currentNode && scope[treeId].currentNode.selected ) {
scope[treeId].currentNode.selected = undefined;
}
//set highlight to selected node
selectedNode.selected = 'selected';
//set currentNode
scope[treeId].currentNode = selectedNode;
};
}
//Rendering template.
element.html('').append( $compile( template )( scope ) );
}
}
};
}]);
})( angular );
My html is -
<div data-angular-treeview="true" data-tree-id="Treevalue"
data-tree-model="suggestionList" data-node-id="id" data-node-class="type" data-node-label="name"
data-node-children="childrens" data-search-query="suggestionListSearchText" data-search-highlight-function="highlightHTML"
data-search-highlight-class-name="searchText" data-search-filter="NameFilter">
</div>
So, How to define a variable in this directive and use it in the scope ?
Looking through the code, it may be as simple as adding HTML inside the div with data-tree-view on it. That HTML will be wiped as part of the tree view directive, so anything you add in there (like a spinner) will be displayed until the directive finishes.
Edit:
Add an image inside the tree view div. This HTML will be cleared, so it will only show while it's loading.
<div data-angular-treeview="true" data-tree-id="Treevalue"
data-tree-model="suggestionList" data-node-id="id" data-node-class="type" data-node-label="name"
data-node-children="childrens" data-search-query="suggestionListSearchText" data-search-highlight-function="highlightHTML"
data-search-highlight-class-name="searchText" data-search-filter="NameFilter">
<img src="spinner.gif">
</div>

How to put id IS NOT NULL with escape varible ??/?

I tried to put 3 variations are included:
empty
version IS NOT NULL AND
version = ' + criteria.version + ' AND
I need use escape
Help please
this code is wrong, but for understanding I need like this:
function getCriteria(criteria){
var ver = '';
if(criteria.version == null){
ver = 'version IS NOT NULL AND';
}
else if(criteria.version > 0)
{
ver = 'version = ' + criteria.version + ' AND';
}
return mysql.getConnection((conn) => {
return conn.queryAsync('SELECT * FROM hlrlookup.hlrlookup ' +
'WHERE ? create_timestamp < "2017-02-16 13:34:40"', [ver]).then............
You could build the query text using regular string handling, but still use the parameterization for the case where you need it;
function getCriteria(criteria) {
var ver = '';
var parms = []
if(criteria.version == null){
ver = 'version IS NOT NULL AND';
}
else if(criteria.version > 0)
{
ver = 'version = ? AND';
parms = [criteria.version]
}
return mysql.getConnection((conn) => {
return conn.queryAsync(
'SELECT * FROM hlrlookup.hlrlookup ' +
'WHERE ' + ver + ' create_timestamp < "2017-02-16 13:34:40"', parms)
.then............

Extension stopped working with Google Chrome manifest v2

I am developing an extension for Google Chrome that was working perfectly, but now stopped working with version 2 of the manifest.
It is giving me the following error:
Uncaught SyntaxError: Unexpected end of input
popup.js:
chrome.tabs.getSelected(null, function (aba) {
link = aba.url;
titulo = aba.title;
document.getElementById('mensagem').value = link;
});
function GrabIFrameURL(feedDescription) {
var regex = new RegExp("iframe(?:.*?)src='(.*?)'", 'g');
var matches = regex.exec(feedDescription);
var url = '';
if (matches.length == 2) {
url = matches[1];
}
var quebra = url.split("/");
return quebra[4];
}
$(document).ready(function () {
if (localStorage.nome == '' || localStorage.nome == null || localStorage.email == '' || localStorage.email == null) {
jQuery('#formulario').hide();
jQuery('#erros').html('Configure seus dados aqui');
}
jQuery("#resposta").ajaxStart(function () {
jQuery(this).html("<img src='img/loading.gif'> <b>Sugestão sendo enviada, aguarde...</b>");
});
jQuery('#submit').click(function () {
var nome = localStorage.nome;
var email = localStorage.email;
var mensagem = titulo + "\n\n<br><br>" + link;
jQuery('#formulario').hide();
jQuery.post('http://blabloo.com.br/naosalvo/mail.php', {
nome: nome,
email: email,
mensagem: mensagem
},
function (data, ajaxStart) {
jQuery('#resposta').html(data);
console.log(data);
});
return false;
});
//Listagem de posts
var bkg = chrome.extension.getBackgroundPage();
jQuery('#close').click(function () {
window.close();
});
jQuery('#markeall').click(function () {
bkg.lidoAll();
$('.naolido').attr('class', 'lido');
});
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
$('.naolido').click(function (e) {
e.preventDefault();
klicked = $(this).attr('id');
console.log(klicked);
bkg.setLido(klicked);
$(this).attr('class', 'lido');
openLink($(this).attr('href'));
});
$('.lido').click(function (e) {
openLink($(this).attr('href'));
});
var openLink = function (link) {
chrome.tabs.create({
'url': link,
'selected': true
});
window.close();
}
});
I think the problem is in this part of popup.js:
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
You problem is actually in background.js on lines 12 and 20, you set localStorage.items to '' initially but then try to run a JSON.parse() on it later, but it's not JSON data so JSON.parse returns Unexpected end of input. And, JSON.parse isn't a function you define but a native browser function so, it shows the error as being on "line 1".
Try defining it as an empty array initially and then "pushing" to it as you are now.

Categories