How to fetch Data from Array in Angular js - javascript

I am on a project in which I want to display data from array into <li> using Angular js
myid =[];
$scope.AddtoCart = function(){
myid.push( $scope.dataToCart);
srvaddtocart.addData(myid);
//console.log($scope.SharedCart);
}
$scope.One = function(){
$scope.AddtoCart();
$scope.SharedCart = myid;
console.log($scope.SharedCart);
$("#close").click(function(){
$(".oxy-product-cart").toggleClass("is-visible");
});
}
this is my js code where SharedCart is storing multiple ID
the output of the SharedCart is something like this
[1190,902,123]
How to display this Array in my HTML page
1190
902
123

<ul>
<li ng-repeat="item in SharedCart">{{item}}</li>
</ul>

Here is a simple example you can add to your HTML view
{{myid}}
<ul>
<li ng-repeat="item in myid">{{item}}</li>
</ul>

Related

How to display following object in angular5 html file?

In the above screenshot console I have an object with 2 values users and tickers. Again each one is array of values.
Now how to display these values in angular5 html template as specified in above screenshot?
I am trying to use ngFor but it is showing errors.
Suppose this is your data:
public data = {
tickers:[
{id:"1",name:"Ticker Name 1", company:"Company 1"},
{id:"2",name:"Ticker Name 2", company:"comapny 2"}
],
users:[
{id:"1",first_name:"User1 ", last_name:"u1last", email:"user1#test.com"},
{id:"2",first_name:"User2", last_name:"u2last", email:"user2#test.com"},
{id:"3",first_name:"User3", last_name:"u3last", email:"user3#test.com"},
{id:"4",first_name:"User4", last_name:"u4last", email:"user4#test.com"}
]
};
public dataKeys; // This will hold the main Object Keys.
The constructor will look something like this:
constructor() {
this.dataKeys = Object.keys(this.data);
}
Here is the simple HTML that you need to write:
<div *ngFor="let key of dataKeys">
<h3>{{ key }}</h3>
<ul>
<li *ngFor="let d of data[key]">{{d.name || d.first_name}}</li>
</ul>
</div>
Here is the complete working plunker for your case:
Click here to view the Working Solution
you can use like that,
<ul>
<P>users</p>
<li *ngFor="let item of object.users; let i = index">
{{i}}. {{item.frist_name}}
</li>
<P>Tickets</p>
<li *ngFor="let item of object.tickers; let i = index">
{{i}}. {{item.name}}
</li>
</ul>
According to the documentation it should be this:
Users:
<ol>
<li *ngFor="let user of users">{{user.first_name}}</li>
</ol>
Tickets:
<ol>
<li *ngFor="let ticket of tickets">{{ticket.name}}</li>
</ol>
You can use json pipe for debug purpose like this:
{{object |json}}
If you want exactly as in picture, look at this solution. With this case, you don't need to manually write first level property names of object in template for using *ngFor

Return data from object and show in <ul> via AngularJS

I have a controller that receive from server the JSON below:
"[{\"nome\": \"Ricardo Andrade\"}]"
My controller is removing the \ by parsing the JSON, my controller is:
app.controller("userLogado", function ($scope, $http) {
//$http.get('web/core/components/home/nav.json').
$http.get('http://localhost:2099/api/autenticacao/NomeUsuarioLogado').
success(function (data) {
debugger;
var result = json_parse(data);
var sNome = '';
$.each(result, function(key, item) {
sNome = item.nome;
});
})
});
My question is, how can I take the result of this controller and show in my HTML using AngularJS?
I tried to use an Alert and got the right name like this: "Ricardo Andrade".
Thanks in advance!
Its as simple as putting attaching the result to the controller.
Once you get the result you want, just attach it to scope.
app.controller("myCtrl", function ($scope, $http) {
$scope.result = "Ricardo Andrade"
});
And the HTML
<div ng-controller="myCtrl">
{{result}}
</div>
If you have more than one name, you will need to ng-repeat the names.
<div ng-controller="myCtrl">
<ul ng-repeat='name in result'>
<li>{{name}}</li>
</ul>
</div>
<ul>
<li ng-repeat="names in result">
[{{$index + 1}}] {{names.nome}}
</li>
</ul>
Have a look at ngRepeat:
Docs: https://docs.angularjs.org/api/ng/directive/ngRepeat
W3Schools: http://www.w3schools.com/angular/angular_directives.asp
EDIT:
I hear it's better to use ng-repeat with arrays, so you might want to do that if you feel like it:
Your controller:
$scope.allNames =[];
app.controller("userLogado", function ($scope, $http) {
//$http.get('web/core/components/home/nav.json').
$http.get('http://localhost:2099/api/autenticacao/NomeUsuarioLogado').
success(function (data) {
debugger;
var result = json_parse(data);
for(var name in result) {
$scope.allNames.push(angular.copy(result[name]));
}
})
});
Your HTML:
<ul>
<li ng-repeat="names in allNames">
[{{$index + 1}}] {{names.nome}}
</li>
</ul>
The ul list must be inside a container with ng-controller attribute.
E.g.
<div ng-controller="userLogado">
<ul list here>
</div>
The benefit of using an array with ng-repeat is that you can filter (Read here) and order (Read here) your data.

JQuery find all elements with a class add their id to a coma separated list

As the title says I want to find all li tags inside an ordered list called #selectable with the class .ui-selected and add their id's to a string with each id separated by a comma.
Here's an example of what my html looks like:
<ol id="selectable">
<li id="1" class="ui-selected"><li>
<li id="2"><li>
<li id="3" class="ui-selected"><li>
<li id="4"><li>
<li id="5" class="ui-selected"><li>
</ol>
Try this:
var selectedIds = $('#selectable .ui-selected').map(function() {
return this.id;
}).get().join(',');
Example fiddle
Was working with my fiddle and couldn't figure out why my test array was returning 10 items in stead of 5. You are not closing your list items use <li></li> in stead of <li><li>.
Your source was missing a /.
I pushed them in an array and converted the array to a string with toString()
var listItems = [];
$('#selectable .ui-selected').each(function(){
var theID = $(this).attr('id');
listItems.push(theID);
});
listItems = listItems.toString();
console.log(listItems);
http://jsfiddle.net/h6G8H/4/

Serializing unordered lists using jquery

I have used Lists within a list and I intend to send the id's using jquery to another php file(updateDB.php).
I tried serializing the list but couldn't get the data. I'm not sure if i've got it right, tried looking around every place but couldn't figure out what's wrong with the code.
<ul>
<li id="recordsArray_<?some number?>"><?php echo content?>`
<ul>
<?php
while (some condition) {
?>
<div>
<li id="subArray_<another number?>"><?php echo content?></li>
</div>
<?php
//conditions - increment within the loop
}
?>
</ul>
</li></ul>
the jquery code is something like this,
$(document).ready(function() {
$(function() {
$("#contentLeft ul").sortable({opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable('serialize') + '&action=updateMenuListings';
$.post("updateDB.php", order, function(theResponse) {
$("#contentRight").html(theResponse);
});
}});
});
$(function() {
$("#contentLeft ul li ul").sortable({opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable('serialize') + '&action=updateSubListings';
$.post("updateDB.php", order, function(theResponse) {
$("#contentRight").html(theResponse);
});
}});
});
});
the id's contentLeft are just the id's for before the lists.
I intend to make it draggable hence used sortable.
On debugging, i'm unable to get any id's of the lists in the variable 'order'.
Please do check out the code and help out.
Thanks
Below you'll find some HTML that is structure like yours along with the JavaScript and jQuery to do what you want. This allows you to move the top level items, with all their respective subitems or just rearrange the subitems. Both options generate a body that you can use in the commented out post line.
You can see it in action here: http://jsfiddle.net/WTjsG/
HTML:
<div id="ContentLeft">Sortable With Update
<ul id="Nav" class="sortable navLevel1">
<li id="Nav_1">Nav1
<!-- NOTE: format id's for UL and LI items as <name>_<int> for serialize to work properly -->
<ul id="NavRecords_1" class="sortable navLevel2">
<li id="Nav1_1">Nav1 Item1</li>
<li id="Nav1_2">Nav1 Item2</li>
<li id="Nav1_3">Nav1 Item3</li>
<li id="Nav1_4">Nav1 Item4</li>
</ul>
</li>
<li id="Nav_2">Nav2
<ul id="NavRecords_2" class="sortable navLevel2">
<li id="Nav2_1">Nav2 Item1</li>
<li id="Nav2_2">Nav2 Item2</li>
<li id="Nav2_3">Nav2 Item3</li>
<li id="Nav2_4">Nav2 Item4</li>
</ul>
</li>
</ul>
</div>
JavaScript w/ jQuery:
$(document).ready(function () {
var isDebugMode = true;
//Set common sort settings for all lists
$(".sortable").sortable({
opacity: 0.6,
cursor: 'move'
});
//Function used to configure update calls for each sort
function setSortAction(selector, updatePage, updateAction, itemLabel) {
$(selector).sortable({
update: function () {
var itemList = $(this).sortable(
"serialize", {
attribute: "id",
key: itemLabel
});
//Create POST request to persist the update
var bodyContent = "action=" + updateAction + "&" + itemList;
if (isDebugMode) { alert("DEBUG: bodyContent = \n" + bodyContent); }
//$.post(updatePage, bodyContent, function (postResult) { alert(postResult); });
}
});
}
//Set sort update action for top level and second level
setSortAction(".navLevel1", "updateDB.php", "updateMenuListings", "record");
setSortAction(".navLevel2", "updateDB.php", "updateMenuItemListings", "record");
});

HTML structure in treeview with jQuery

I need to display a HTML structure in a treeview. I found some jQuery treeview plugins but they generally require a list.
Let's take a simple HTML (nodes may have different tags, not only 'div'):
<div id="node1">
<div id="node2">
<div id="node3"></div>
<div id="node4"></div>
</div>
<div>
I want to display it like this:
node1
node2
node3
node4
For now, i'm using this jQuery plugin: treeview
So I need to convert the HTML to an unordered list like this:
<ul>
<li>node1
<ul>
<li>node2
<ul>
<li>node3</li>
<li>node4</li>
</ul>
</li>
</ul>
</li>
</ul>
How can I do this using jQuery? If you think a different approach would be better, please let me know.
Here you go...that was fun. Demo - Updated to not be specific to div tags, and return an element, that could be turned into a html string.
$.fn.convertToUL = function(isTop) {
if(isTop==null) isTop=true;
var ul=$("<ul>");
var li=$("<li>");
li.append($(this).attr("id"));
var children=0;
$(this).children().each(function(){
ul.append($(this).convertToUL(false));
children++;
});
if(children>0)
li.append(ul);
if(li.is(':empty'))
return "";
if(isTop)
return $("<ul>").append(li);
return li;
}
//to get text of elements use .wrap('<div/>').parent().html()
var ulElement=$("#node1").convertToUL();
alert(ulElement.wrap('<div/>').parent().html());
$("#node1").replaceWith(ulElement);

Categories

Resources