Angular/Javascript - change class after data of ng-repeat reloaded - javascript

I am using angularJs with cordova.
I have a ng-repeat, on each items I have a ng-click which put the value of each item in a array. Moreover when I click, it is removing and adding a new class to the div (with the $index of ng-repeat). Like a checklist.
The fact is when, I reload that ng-repeat, I lost the classes I just added when I clicked on it.
I tried (with the array which has not changed) to re-add the class when I call the function that reload the items shown by the ng-repeat. But it doesn't add the class :/
Here are my code :
<div id="ami" class="list-group">
<div href="#" class="list-group-item" ng-repeat="ami in listeAmis"> {{ami.pseudo}}<i id="checkAmi{{$index}}" class="fa fa-circle-o pull-right" ng-click="mapCtrl.checkAmi(ami.pseudo, $index);"></i><i class="fa fa-user pull-left" ></i></div>
</div>
Javascript
var amisNotifies = [];
mapCtrl.checkAmi = checkAmi;
function checkAmi(pseudo, id) {
var info = ({
pseudo: pseudo,
id: id
});
var getIndexOf = function (psdu) {
for (var i = 0; i < amisNotifies.length; i++) {
if (amisNotifies[i].pseudo === psdu) {
return i;
}
}
return -1;
};
if (amisNotifies.length > 0) {
var index = getIndexOf(pseudo);
if (index > -1) {
//so already exists. now remove it.
Array.prototype.splice.call(amisNotifies, index, 1);
$("#checkAmi" + id).addClass("fa-circle-o");
$("#checkAmi" + id).removeClass("fa-check-circle-o");
}
else {
//does not exist, now add it
amisNotifies.push(info);
$("#checkAmi" + id).removeClass("fa-circle-o");
$("#checkAmi" + id).addClass("fa-check-circle-o");
}
} else {
amisNotifies.push(info);
$("#checkAmi" + id).removeClass("fa-circle-o");
$("#checkAmi" + id).addClass("fa-check-circle-o");
}
console.log(amisNotifies);
}
And so, when I reload the data shown by the ng-repeat I tried to put it but it doesn't change the class again...
if (amisNotifies.length > 0) {
for (var i = 0; i < amisNotifies.length; i++) {
console.log(amisNotifies[i].id);
$("#checkAmi" + amisNotifies[i].id).removeClass("fa-circle-o");
$("#checkAmi" + amisNotifies[i].id).addClass("fa-check-circle-o");
}
}

HTML with dynamic ng-class stocked in array depending of the index :
<div id="ami" class="list-group">
<div href="#" class="list-group-item" ng-repeat="ami in listeAmis"> {{ami.pseudo}}
<i id="checkAmi{{$index}}" ng-class="isChecked[{{$index}}]" ng-click="mapCtrl.checkAmi(ami.pseudo, $index);"></i>
</div>
</div>
Declare the numbers of variable depending the size of ng-repeat :
if ($scope.listeAmis.length > 0) {
for (var j = 0; j < $scope.listeAmis.length; j++) {
$scope.isChecked[j] = "fa fa-circle-o pull-right";
}
}
Check the line you just clicked on and change the ng-class (moreover I stock the index of the line a just clicked in order to declare $scope.isChecked[j] differently if I clicked on it ...
mapCtrl.checkAmi = checkAmi;
function checkAmi(pseudo, id) {
var info = ({
pseudo: pseudo,
id: id
});
var getIndexOf = function (psdu) {
for (var i = 0; i < amisNotifies.length; i++) {
if (amisNotifies[i].pseudo === psdu) {
return i;
}
}
return -1;
};
if (amisNotifies.length > 0) {
var index = getIndexOf(pseudo);
if (index > -1) {
//so already exists. now remove it.
Array.prototype.splice.call(amisNotifies, index, 1);
$scope.isChecked[id] = "fa fa-circle-o pull-right";
} else {
//does not exist, now add it
amisNotifies.push(info);
$scope.isChecked[id] = "fa fa-check-circle-o pull-right";
}
} else {
amisNotifies.push(info);
$scope.isChecked[id] = "fa fa-check-circle-o pull-right";
}
console.log(amisNotifies);
}

Related

Splicing only one element when creating a new element

I'm trying to make it where when a user creates a widget, and then reloads the page (it'll appear because it's saved in localStorage) and then once you create another widget, I want to be able to delete the old widget before the page refreshes but it deletes the widget that the user clicked and the new widget.
Each time a new widget it created, it gets assigned a property name 'id' and the value is determined based on what is already in localStorage and it finds the next available (or not in use) id number. The widgets array also gets sorted from smallest id to largest id before setting it back to localStorage.
I've tried attaching a click listener for the delete button on the widget both when it's created and when the document is loaded. But that wasn't working.
Now i'm thinking I have to call a function with the id as its param to add a click listener to all the widgets that are appended to the document and when a new widget is created.
app.js:
function addRemoveListener(id) {
let storageUi = localStorage.getItem('ui');
let localUi = JSON.parse(storageUi);
$(`#widget-${id} > span > .widget-clear`).click(() => {
for (let i = 0; i < localUi.widgets.length; i++) {
let thisWidget = `#widget-${id}`;
if (localUi.widgets[i].id == id) {
localUi.widgets.splice(i, 1)
}
$(thisWidget).remove();
console.log(localUi)
}
let newUi = JSON.stringify(localUi);
localStorage.setItem('ui', newUi);
})
}
widget.js:
static appendToDom(ui) {
let storageUi = localStorage.getItem('ui');
let localUi = JSON.parse(storageUi);
for (let i = 0; i < localUi.widgets.length; i++) {
let widget = localUi.widgets[i];
let query = () => {
if (widget.type == 'humidity') {
return `${Math.floor(ui.weather.currently.humidity * 100)}`
} else if (widget.type == 'eye') {
return `${Math.floor(ui.weather.currently.visibility)}`
} else if (widget.type == 'windsock') {
return `${Math.floor(ui.weather.currently.windSpeed)}`
} else if (widget.type == 'pressure') {
return `${Math.floor(ui.weather.currently.pressure)}`
} else if (widget.type == 'uv-index') {
return `${ui.weather.currently.uvIndex}`
}
}
$('nav').after(`<div class="widget widget-${widget.size}" id="widget-${widget.id}">
<span>
<i class="material-icons widget-clear">clear</i>
<i class="material-icons widget-lock-open">lock_open</i>
<i class="material-icons widget-lock">lock_outline</i>
</span>
<div class="data-container">
<img src=${widget.image}>
<h1> ${widget.type}: ${query()} ${widget.unit} </h1>
</div>
</div>`)
$(`#widget-${widget.id}`).delay(1000 * i).animate({ opacity: 1 }, 1000);
$(`#widget-${widget.id}`).css({ left: `${widget.left}`, top: `${widget.top}`, 'font-size': `${widget.dimensions[2]}` })
$(`.widget`).draggable();
$(`#widget-${widget.id}`).css({ width: `${widget.dimensions[0]}`, height: `${widget.dimensions[1]}` })
addRemoveListener(i);
}
// this function is called earlier in the script when the user has selected
// which kind of widget they want
let makeWidget = () => {
let newWidget = new Widget(this.size, this.id, this.image, this.type, this.unit, this.dimensions);
saveWidget(newWidget);
addRemoveListener(this.id)
}
I have no problems with this until I delete an existing widget after I create a new one, and before refreshing.
You might have a problem with the id that is passed to your addRemoveListener function. It could be passing the same id for any widget so the loop will delete the UI because thisWidget is in the for loop. Try adding some console logging.
function addRemoveListener(id) {
let storageUi = localStorage.getItem('ui');
let localUi = JSON.parse(storageUi);
$(`#widget-${id} > span > .widget-clear`).click(() => {
for (let i = 0; i < localUi.widgets.length; i++) {
let thisWidget = `#widget-${id}`;
if (localUi.widgets[i].id == id) {
localUi.widgets.splice(i, 1)
}
// Move this inside the if statement above.
$(thisWidget).remove();
console.log(localUi)
}
let newUi = JSON.stringify(localUi);
localStorage.setItem('ui', newUi);
})
}
or better yet, re-write it to continue if the id doesn't match
function addRemoveListener(id) {
let storageUi = localStorage.getItem('ui');
let localUi = JSON.parse(storageUi);
$(`#widget-${id} > span > .widget-clear`).click(() => {
for (let i = 0; i < localUi.widgets.length; i++) {
let thisWidget = `#widget-${id}`;
if (localUi.widgets[i].id !== id) {
continue;
}
localUi.widgets.splice(i, 1)
$(thisWidget).remove();
console.log(localUi)
}
let newUi = JSON.stringify(localUi);
localStorage.setItem('ui', newUi);
})
}

Javascript menu dropdown not triggering function on click

So i've been messing around and searching and it triggers when i don't generated the code via my JS and put the output as html on the file.
The menu is supposed to be dynamic and generate subs on it and subs have products and so on i was doing it and logically is correct but can't know if JS is confliting some part of this code.
JS Generate Menus:
$(function(){
var ul = $('#category-content');
var subcategoryLi = $('#sublist');
var productsLi = $('#productList');
init();
function init(){
GetCategorys();
}
function BuildSubCategorys(id,sub){
var content = '';
if (typeof(sub) != 'undefined' && sub.length > 0){
for(var i = 0; i < sub.length; i++){
if (sub[i].c_parentcat == id){
content += AddSubItem(sub[i].c_name,sub[i].c_id);
}
}
return content;
}
else{
return '';
}
}
function hasSubs(j,d){
for(var i=0;i<d.length;i++){
if(d[i].c_parentcat == j ){
return true;
}
}
}
function BuildCategorys(root){
var content = AddCategoryHeader('Categorias');
var subs = [];
if (typeof(root) != 'undefined' && root.length > 0){
for(var i = 0; i < root.length; i++){
if (root[i].c_parentcat == -1){
content += AddCategory(root[i].c_name,root[i].c_id);
if (hasSubs(root[i].c_id, root) == true){
var subContent = BuildSubCategorys(root[i].c_id, root);
subs[root[i].c_id] = CreateSubList(subContent);
}
}
}
ul.append(content);
ul.append(AddSeparator());
for(var j = 0; j < root.length; j++){
curr_id = root[j].c_id;
ul.find('#category'+curr_id).append(subs[curr_id]);
}
}
else {
ul.append(AddCategoryHeader('Categorias'));
ul.append(HandleNoSubData());
ul.append(AddSeparator());
}
//Build the products
GetCategoryProducts();
}
function BuildProducts(p){
var content = AddCategoryHeader('Produtos sem categoria');
var category_items = [];
if (typeof(p) != 'undefined' && p.length > 0){
for(var i=0; i < p.length; i++){
if (p[i].p_categoryid == -1){
//he has no category so lets add it to the non category section
content += AddProduct(p[i].p_name,p[i].p_id);
}
else {
subcategoryLi.find('#subcategory'+ p[i].p_categoryid).append(AddProduct(p[i].p_name,p[i].p_id));
}
}
ul.append(content);
//LEFT: LINK ON THE PRODUCT WITH THEIR ID ON CREATE FUNCTION
}else{
ul.append(AddCategoryHeader('Produtos sem categoria'))
ul.append(HandleNoProdData());
}
}
function AddSeparator(){
return '<li role="separator" class="divider"></li>';
}
function AddCategoryHeader(name){
return '<li class="dropdown-header">' + name +'</li>';
}
function AddCategory(name,id){
return '<li class="dropdown-submenu" id="category'+id+'"><a id="menu-itex" tabindex="-1" href="javascript:;">' + name + ' <span class="caret"></span></a></li>';
}
function AddProduct(name,id){
return '<li>' + name + '</li>';
}
function AddSubItem(name,id){
return '<li> '+ name + ' </li>';
}
function CreateSubList(c){
return '<ul id="sublist" class="dropdown-menu">'+ c +'</ul>';
}
function CreateProductsList(){
return '<li class="dropdown"><ul id="productList" class="dropdown-menu">'+ c +'</ul></li>';
}
function HandleNoData(){
return '<li> Não existem categorias </li>';
}
function HandleNoSubData(){
return '<li> Não existem sub-categorias </li>';
}
function HandleNoProdData(){
return '<li> Não existem produtos </li>';
}
function GetCategorys(){
var url = base_url + 'home/ajaxCategorys';
$.post(url,function(js){
if (js != null && js != 'false')
BuildCategorys(JSON.parse(js));
else
return false;
});
}
function GetCategoryProducts(){
var url = base_url + 'home/ajaxCategoryProducts';
$.post(url,function(js){
if (js != null && js != 'false')
BuildProducts(JSON.parse(js));
else
return false;
});
}
$(document).ready(function(){
$('#menu-itex').on("click" ,function(e){
console.log('Click for menu');
$(this).next('ul').toggle();
e.stopPropagation();
e.preventDefault();
});
});
});
The output of my code directly as html it works but if i do in this way with JS script on generating it it doesn't trigger on menu-itex id click and i also tried by using the class. Got the trigger idea from w3wschools boostrap advanced menus.
When you add a event listener to a generated element before the item is generated (happens sometimes), it'll not trigger the event on click.
The best solution is to append the click event to body (or the item container that is rendered on page load) and listen to click only if it's inside the desired element.
It goes something like this:
//$('body').on('click', <-- would work too, but it's not delimited to a certain section of your page.
$('#category-content').on('click', '#menu-itex', function(){
//Your stuff here
})

Paginition refresh issue in AngularJS

I am showing items using pagination in AngularJS.
For example, I have 12 items and number of items per page is 5. So I have 3 pages to show with the first two pages have 5 items each and the last page has two items.
When I switch pages, say from page-1 to page-2, all 10 items from both page-1 and page-2 are displayed together for a while first before the page-2 items are displayed.
Same thing happened from page-2 to page-3, all 7 items from both page-2 and page-3 are displayed together for a while first before the page-3 items are displayed.
Whenever I switch pages, the same thing is observed.
What could be wrong?
My code is as follow.
html
<div class="adds-wrapper">
<div ng-show="Available">
<div class="item-list" ng-repeat="hotel in pagedItems[currentPage]">
<!-- this is how items are displayed -->
</div>
<div class="pagination-bar">
<ul class="pagination">
<li ng-class="{disabled: currentPage == 0}">
<a class="pagination-btn" href ng-click="prevPage()">« Prev</a></li>
<li ng-repeat="n in range(pagedItems.length)" ng-class="{active: n == currentPage}" ng-click="setPage()">
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: currentPage == pagedItems.length - 1}">
<a class="pagination-btn" href ng-click="nextPage()">Next »</a></li>
</ul>
</div>
Javascript
function groupToPages() {
$scope.pagedItems = [];
for (var i = 0; i < $scope.filteredItems.length; i++) {
var j = Math.floor(i / $scope.itemsPerPage);
if (i % $scope.itemsPerPage === 0) {
$scope.pagedItems[j] = [$scope.filteredItems[i]];
} else {
$scope.pagedItems[j].push($scope.filteredItems[i]);
}
}
};
var loadPagination = function () {
$scope.sortingOrder = $scope.sortingOrder;
$scope.reverse = false;
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 5;
$scope.pagedItems = [];
$scope.currentPage = 0;
$scope.items = $scope.HotelAndResorts;
$scope.filteredItems = $scope.HotelAndResorts;
$scope.hotelAvailable = true;
if ($scope.HotelAndResorts) {
if ($scope.HotelAndResorts.length == 0) {
$scope.hotelAvailable = false;
$scope.errorMessage = "No Post Found.";
}
} else {
$scope.hotelAvailable = false;
$scope.errorMessage = "No Post Found."
}
/*var searchMatch = function (haystack, needle) {
if (!needle) {
return true;
}
return haystack.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
};*/
groupToPages();
$scope.range = function (start, end) {
var ret = [];
if (!end) {
end = start;
start = 0;
}
for (var i = start; i < end; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function () {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.nextPage = function () {
if ($scope.currentPage < $scope.pagedItems.length - 1) {
$scope.currentPage++;
}
};
$scope.setPage = function () {
$scope.currentPage = this.n;
};
$scope.sort_by = function (newSortingOrder) {
if ($scope.sortingOrder == newSortingOrder)
$scope.reverse = !$scope.reverse;
$scope.sortingOrder = newSortingOrder;
// icon setup
$('th i').each(function () {
// icon reset
$(this).removeClass().addClass('icon-sort');
});
if ($scope.reverse)
$('th.' + new_sorting_order + ' i').removeClass().addClass('icon-chevron-up');
else
$('th.' + new_sorting_order + ' i').removeClass().addClass('icon-chevron-down');
};
}
When you paginate after updating the paged items try calling $scope.apply() this tells AngularJS to look fixup various javascript things. Angular does some sorcery under the hood to make Javascript behave asynchronously, apply makes thing sync up. I'm oversimplifying, if you like you can read the exact documentation, but I find when htis kind of thing happens 95% of the time it's because I didn't apply.

Remove array value if already exists javascript

I've got an array of values that i show with an ng-repeat. When i click over one of it, i add this value in another array. If already exists i remove it. It works well here. But i have a button that push all array in the second. It's working but i can push the whole array infite times even if a value already exists. Of course, if i check one or two value and then i push "Select all" it must select all values also the values already select with the single selection. By thge way this is the code with a jsfiddle:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.all_titles = [
"Title 1",
"Title 2",
"Title 3",
"Title 4"
];
$scope.selection=[];
$scope.getSelectedItem = function getSelectedItems(title) {
var idx = $scope.selection.indexOf(title);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
if(Array.isArray(title)) {
for(var i=0;i<title.length;i++) {
$scope.selection.push(title[i]);
}
} else {
$scope.selection.push(title);
}
}
};
}
<div ng-controller="MyCtrl">
<div>
<button data-ng-click="getSelectedItem(all_titles)">
Select all
</button>
</div>
<div ng-repeat="title in all_titles">
<a ng-click="getSelectedItem(title)">{{title}}</a>
</div>
<hr>
<div>
{{selection}}
</div>
</div>
http://jsfiddle.net/HB7LU/20342/
You scenario is not quite clear to me.
If you want the select all button to behave like all links are click, then this is your solution:
$scope.getSelectedItem = function getSelectedItems(title) {
if(Array.isArray(title)) {
for(var i=0;i<title.length;i++) {
$scope.pushIt(title[i]);
}
} else {
$scope.pushIt(title);
}
};
$scope.pushIt = function pushIt(title) {
var idx = $scope.selection.indexOf(title);
// remove if already in array
if (idx > -1) {
$scope.selection.splice(idx, 1);
} else {
$scope.selection.push(title);
}
};
If you want the select all button to add the remaining items, then this is your solution:
$scope.getSelectedItem = function getSelectedItems(title) {
if (Array.isArray(title)) {
for (var i = 0; i < title.length; i++) {
var idx = $scope.selection.indexOf(title[i]);
// don't add if already in the array
if (idx == -1) {
$scope.selection.push(title[i]);
}
}
} else {
var idx = $scope.selection.indexOf(title);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
} else {
$scope.selection.push(title);
}
}
};
Your code is work, but you need to create a else
for(var i=0;i<title.length;i++) {
var n_idx = $scope.selection.indexOf(title[i]);
if( n_idx == -1){
$scope.selection.push(title[i]);
}else{
$scope.selection.splice(n_idx, 1);
}
}
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.all_titles = [
"Title 1",
"Title 2",
"Title 3",
"Title 4"
];
$scope.selection=[];
$scope.getSelectedItem = function getSelectedItems(title) {
var idx = $scope.selection.indexOf(title);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
if(Array.isArray(title)) {
console.log("YES");
for(var i=0;i<title.length;i++) {
var n_idx = $scope.selection.indexOf(title[i]);
if( n_idx == -1){
$scope.selection.push(title[i]);
}else{
$scope.selection.splice(n_idx, 1);
}
}
} else {
$scope.selection.push(title);
}
}
};
}
Netzach is right concerning the bug.
Also I would optimise your code by using hash instead of looping over the array. Then the code excluding/including the value will look like:
if($scope.selection[title]){
delete $scope.selection[title];
} else {
$scope.selection[title] = true;
}
Here is jsfiddle to a working example:
http://jsfiddle.net/HB7LU/20348/

How to get the ancestors of a JS tree node when it is selected?

I am getting the child tree name but I want to get its complete hierarchy of parent node names.
Below code shows how I get the child node and print its value in a particular div element:
$(document).ready(function () {
$('#bdeViewNew').on('changed.jstree', function (e, data) {
var i, j, r = [];
for (i = 0, j = data.selected.length; i < j; i++) {
r.push(data.instance.get_node(data.selected[i]).text.trim());
$('#treeBreadCrumbs').html(r.join(', '));
}
});
});
Now it prints the value of child node, e.g. Child a. But I want something like follows, if the tree structure is as shown below:
Parent
Child 1
Child a
Child b
Child 2
Child c
Child d
so if I click on Child a I want my div content updated as
Parent > Child 1 > Child a
as of now I am getting Child a only. Please let me know how I can get the correct output.
I tried like this as shown below to get path of all the parent node:
$(document).ready(function() {
$('#bdeViewNew').on('changed.jstree', function(e, data) {
var ids = data.inst.get_path('#bdeViewNew' + data.rslt.obj.attr('id'),true);
var names = data.inst.get_path('#bdeViewNew' + data.rslt.obj.attr('id'),false);
alert("Path [ID or Name] from root node to selected node = ID's = "+ids+" :: Name's = "+names);
});
});
but still no result to get_path. Do I need to use different JS or a plugin? And what is the meaning of attr('id') i should pass the id of that li or something else as i did'nt understand this syntax properly.
Adding my jstree:
<div id="bdeViewNew">
<ul>
<li id="bde" data-jstree='{"opened":true,"icon":"./images/tree.png"}'">
Parent 1
<ul>
<li id="aaa" data-jstree='{"opened":true,"icon":"./images/tree.png"}'>
Child 1 <c:forEach items="${empInfo.empList}"
var="empValue">
<ul>
<li id="bbb" data-jstree='{"icon":"./images/tree.png"}' >${empValue.empName}</li>
</ul>
</c:forEach>
</li>
</ul>
<ul>
<li id="ccc" data-jstree='{"icon":"./images/tree.png"}'>Child 2
<c:forEach items="${imgInfo.imgList}"
var="imgValue">
<ul>
<li id="ddd" data-jstree='{"icon":"./images/tree.png"}'>${imgValue.imgName}</li>
</ul>
</c:forEach>
</li>
</ul>
</li>
</ul>
</div>
This will work fine... it will get the full parents...
$('#bdeViewNew').on('select_node.jstree', function (e, data) {
var loMainSelected = data;
uiGetParents(loMainSelected);
});
function uiGetParents(loSelectedNode) {
try {
var lnLevel = loSelectedNode.node.parents.length;
var lsSelectedID = loSelectedNode.node.id;
var loParent = $("#" + lsSelectedID);
var lsParents = loSelectedNode.node.text + ' >';
for (var ln = 0; ln <= lnLevel -1 ; ln++) {
var loParent = loParent.parent().parent();
if (loParent.children()[1] != undefined) {
lsParents += loParent.children()[1].text + " > ";
}
}
if (lsParents.length > 0) {
lsParents = lsParents.substring(0, lsParents.length - 1);
}
alert(lsParents);
}
catch (err) {
alert('Error in uiGetParents');
}
}
var node=$('#drives_tree').jstree("get_selected", true);
$("#breadcrumbs").text($('#drives_tree').jstree().get_path(node[0], ' > '));
We have direct method to get the parent information.
$('#bdeViewNew').on('select_node.jstree', function (e, data) {
var loMainSelected = data;
alert(loMainSelected.node.parents);
});
It will return ["Child1", "Parent"] . Using this method we can get the all the parents up to root.
function uiGetParents(loSelectedNode) {
try {
var loData = [];
var lnLevel = loSelectedNode.node.parents.length;
var lsSelectedID = loSelectedNode.node.id;
var loParent = $("#" + lsSelectedID);
var lsParents = loSelectedNode.node.text + ' >';
for (var ln = 0; ln <= lnLevel - 1 ; ln++) {
var loParent = loParent.parent().parent();
if (loParent.children()[1] != undefined) {
lsParents += loParent.children()[1].text + " > ";
loData.push(loParent.children()[1].text);
}
}
if (lsParents.length > 0) {
lsParents = lsParents.substring(0, lsParents.length - 1);
}
alert(lsParents);
alert(loData.reverse());
}
catch (err) {
alert('Error in uiGetParents');
}
}
The result stored in array loData . and just reverse the data and loop the loData Array. You got u r output
**
Step 1 : Get the Selected node Id and selected node level
Step 2 : Using node id get the current parent like this ( ex.. $("#101000000892").parent().parent() )
step 2.2 : Next level node ( $("#101000000892").parent().parent().parent().parent() )
step 2.3 : stroe this in a vairable var loNode = $("#101000000892").parent().parent();
step 2.4 : Next you can loNode.parent().parent()
Step 3 : Using for loop u can loop through the level until reached 1.
step 4 : Now you can get the full text .
**
Try this,
Instead of angular.each, use a for loop.
You will get an arry with all the text of the nodes.
var breadcrumbArr = [selectedNode.node.text];
angular.forEach(selectedNode.node.parents, function(element, index) {
if (element === '#') return;
breadcrumbArr.push($('#'+element).find('a:first').text())
});
breadcrumbArr.reverse();
return breadcrumbArr;
A slightly less verbose version that prints Parent > Child
function uiGetParents(node) {
try {
var level = node.node.parents.length;
var elem = $('#' + node.node.id);
var text = node.node.text;
for (var ln = 0; ln <= level - 1 ; ln++) {
elem = elem.parent().parent();
var child = elem.children()[1];
if (child != undefined) {
text = child.text + ' > ' + text;
}
}
console.log(text);
}
catch (err) {
console.log('Error in uiGetParents');
}
}
var node = $tree.jstree().get_node(id),
formatted_name = $tree.jstree().get_text(node);
$.each(node.parents, function(key, parentId) {
if ( parentId !== "#" ) {
var parent = $tree.jstree().get_node(parentId);
formatted_name = $tree.jstree().get_text(parent) + "->" + formatted_name;
}
});
console.log(formatted_name);

Categories