please am very new new to angular and am trying to do something i don't know if its possible. I have a json data and i want to render the option on click of an item. What i want to achieve is to show models of a phone on click of the name, and on click of a phone model show all the phone parts. But whenever i click on a phone i get undefined in my console.
my app.js file
(function(){
var app=angular.module('repairshop',[]);
app.controller('phoneController',function($scope){
this.phones = [
{
name: 'Apple',
model: [{ name: 'Iphone 5'}, {name: 'Iphone 6'},{name: 'Iphone 6s'}],
part: [{name:'ear phones'},{name:'external speakers'},{name:'Screen Guard'},{name:'Charger'}]
},
{
name: 'Samsung',
model: [{ name: 'S4'}, {name: 'S5'},{name: 'S6'}],
part: [{name:'ear phones'},{name:'external speakers'},{name:'Screen Guard'},{name:'Charger'}]
},
{
name: 'Nokia',
model: [{ name: 'Lumia'}, {name: '3310'},{name: 'Asha'}],
part: [{name:'ear phones'},{name:'external speakers'},{name:'Screen Guard'},{name:'Charger'}]
},
{
name: 'Blackberry',
model: [{ name: 'Passport'}, {name: 'Touch 10'},{name: 'Asha'}],
part: [{name:'ear phones'},{name:'external speakers'},{name:'Screen Guard'},{name:'Charger'}]
}
];
$scope.loadModels=function(phone)
{
var phone=phone.name;
console.log (phone);
}
});
})();
My Html View
<div class="phones_wrapper row">
<!--begin container-->
<div class="container">
<form class="" action="#" method="post" ng-controller="phoneController as phone" >
<div class="row">
<div class="col-md-3 phone_display center" ng-repeat="p in phone.phones">
<label>
<input type="radio" ng-click="loadModels(phone)" ng-model="phone.name" name="phone" ng-value="{{p.name}}" />
<img src="http://placehold.it/200x200">
</label>
<p class="text text-center phone_name">{{p.name}}</p>
</div>
</div>
</form>
</div>
<!--begin container-->
</div>
Here is a simple example plnkr on how you can click on the list of the items you describe to view more details such as models and parts.
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="phone in phones" ng-click="showModels = true">{{phone.name}}
<ul ng-show="showModels">
<li ng-repeat="model in phone.model" ng-click="showParts = true">{{model.name}}
<ul ng-show="showParts">
<li ng-repeat="part in phone.part">
{{part.name}}
</li>
</ul>
</li>
</ul>
</li>
</ul>
</body>
Basically what you have to do is add repeaters and ng-click events to expand the content. I am pretty sure that from this example you will be able to fix it with your own styling and markup.
Edit:
A better example where you can toggle the viewing of models and parts.
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="phone in phones" ng-click="showModels = !showModels; $event.stopPropagation()">{{phone.name}}
<ul ng-show="showModels">
<li ng-repeat="model in phone.model" ng-click="showParts = !showParts; $event.stopPropagation()">{{model.name}}
<ul ng-show="showParts">
<li ng-repeat="part in phone.part">
{{part.name}}
</li>
</ul>
</li>
</ul>
</li>
</ul>
</body>
I found it, i changed the loadModels function to
$scope.loadModels=function(phone)
{
phone.parent=phone.name;
console.log (phone);
}
and also changed the phone to p based on #Praneeth Gudumasu recommendation. Thank you
it should be like this
<div class="col-md-3 phone_display center" ng-repeat="p in phone.phones">
<label>
<input type="radio" ng-click="loadModels(p)" ng-model="p.name" name="phone" ng-value="{{p.name}}" />
<img src="http://placehold.it/200x200">
</label>
<p class="text text-center phone_name">{{p.name}}</p>
</div>
you should use the repeating object inside the repeating template and not the scope object(in your case variable "p" not "phone")
Related
**So, I have this table that displays users taken from a server in angularjs. Here is the users object:
:**
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
Here html :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="namesCtrl">
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter:test">
{{ x }}
</li>
</ul>
</div>
You can hide list until user enters something in input like
<ul ng-if="test">
...
</ul>
In my Angular app I have the following menu:
As you can see I have items (that are a elements) and a checkbox and a label in each of them:
<span class="caption">RAM</span>
<a class="item">
<div class="item-checkbox">
<input type="checkbox" tabindex="0" class="hidden">
<label>4 GB</label>
</div>
</a>
<a class="item">
<div class="item-checkbox">
<input type="checkbox" tabindex="0" class="hidden">
<label>8 GB</label>
</div>
</a>
<a class="item">
<div class="item-checkbox">
<input type="checkbox" tabindex="0" class="hidden">
<label>16 GB</label>
</div>
</a>
How should I add (click) to every item to correctly handle event capturing so if user click on label or on whole item I get the related checkbox selected?
...Or do you know a better way to reach what I mean?
To make sure that clicking on the label toggles the checkbox, include the input element inside of the label (as explained in MDN):
<a class="sub-item item">
<div class="item-checkbox">
<label><input type="checkbox" tabindex="0" class="hidden">4 GB</label>
</div>
</a>
If you also want the label to fill the anchor element, define the CSS as shown below. With this styling in place, clicking on the anchor will toggle the checkbox.
.ui.secondary.menu a.item {
padding: 0px;
}
div.item-checkbox {
width: 100%;
height: 100%;
}
div.item-checkbox > label {
display: block;
padding: .78571429em .92857143em;
}
div.item-checkbox > label > input {
margin-right: 0.25rem;
}
See this stackblitz for a demo.
If you can place all the checkboxes in a container, you can set a single click event listener on the container, and event.target will give you the clicked element and previousElementSibling will select the sibling input.
function doSomething() {
const selectedInput = event.target.previousElementSibling;
selectedInput.checked = selectedInput.checked? false : true;
}
But in case there is a probability that you document structure changes in the future, say for example, if other elements get in between the input and the label, or their order changes, then the sibling selector will fail. To solve this you can use a parent selector instead and select the chechbox input element inside of it.
document.getElementById('container').addEventListener('click', doSomething);
function doSomething() {
const selectedElement = event.target.parentElement.querySelector('input[type="checkbox"]');
selectedElement.checked = selectedElement.checked? false:true;
}
<div id= 'container'>
<span class="caption">RAM</span>
<a class="item">
<div class="item-checkbox">
<input type="checkbox" tabindex="0" class="hidden" value="4 GB">
<label>4 GB</label>
</div>
</a>
<a class="item">
<div class="item-checkbox">
<input type="checkbox" tabindex="0" class="hidden" value="8 GB">
<label>8 GB</label>
</div>
</a>
<a class="item">
<div class="item-checkbox">
<input type="checkbox" tabindex="0" class="hidden" value="16 GB">
<label>16 GB</label>
</div>
</a>
</div>
First of all you should use *ngFor to list all your options:
html:
<a class="item" *ngFor="let choice of checks; let i=index">
<div class="item-checkbox">
<input type="checkbox" tabindex="0" class="hidden" [value]="choice.value" (change)="onCheckChange($event)">
<label>{{choice.title}}</label>
</div>
</a>
component:
public checks: Array<choices> = [
{title: '4 GB', value: '4'},
{title: "8 GB", value: '8'},
{title: "16 GB", value: '16'}
];
public onCheckChange(event) {
// do some things here
}
Further, you should use Reactive Forms to validate your choices:
https://angular.io/guide/reactive-forms
You have to create a boolean array and bind this to your checkboxes.
.ts file
myArray: any[] = [
{
"size": "2GB",
"value":false
},
{
"size": "4GB",
"value":false
},
{
"size": "8GB",
"value":false
}
]
.html file
<div *ngFor="let data of myArray">
<a class="item">
<div class="item-checkbox">
<input type="checkbox" tabindex="0" class="hidden" [(ngModel)]="data.value" (ngModelChange)="changeHandler()">
<label>{{data.size}}</label>
</div>
</a>
</div>
Working demo : link
You could do something like that:
const ramOptions = [
{
id: 1,
size: '4 GB'
},
{
id: 2,
size: '8 GB'
},
{
id: 3,
size: '16 GB'
}
]
And in html:
<a class="item" *ngFor="let option of ramOptions">
<div class="item-checkbox">
<input type="checkbox" tabindex="0" class="hidden" (change)="onSelect(option.id)">
<label>{{option.size}}</label>
</div>
</a>
If in the .js/.ts file, you can create an interface to define the handler. Just as:
onSelect(id: string) {
...
}
How can I use ng-repeat to loop over data that contains many nested array data?
I have data that will have many "Segments"
Example:
confirm.booking.flightData[0].Segments[0].FlightNumber
confirm.booking.flightData[0].Segments[1].FlightNumber
confirm.booking.flightData[0].Segments[2].FlightNumber
I have done both ng-repeat with angular, and without angular I would end up resorting to javascript that loops over data and creates the html dynamically, but I wish to do this the ANGULAR way.. HOW?
HTML with Angular/Javascript Arrays:
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<span style="font-weight: bold;">Flight</span>
</div>
<div class="col-md-4">
<span style="font-weight: bold;">Departs</span>
</div>
<div class="col-md-4">
<span style="font-weight: bold;">Arrives</span>
</div>
</div>
<div class="row">
<div class="col-md-4">
{{confirm.booking.flightData[0].Segments[0].FlightNumber}}
</div>
<div class="col-md-4">
({{confirm.booking.flightData[0].Segments[0].DepartureAirport}})
</div>
<div class="col-md-4">
({{confirm.booking.flightData[0].Segments[0].ArrivalAirport}})
</div>
</div>
</div>
Nesting can be done in repeats, but repeating too much in ng-repeats can be costly in terms of performance as angular creates scopes for each element repeated. Hence, filtering data till the perfect abstracted values that you need in terms of html should be done in the js file.
For eg: if u need only segements in the html form do this, or if u need even flight data in html form follow #Rachel's post
<ul data-ng-repeat="item in confirm.booking.flightData[0].Segments">
<li>{{ item.FlightNumber}}</li>
</ul>
Let's say your data is in flightdetails, then you can go about it like this:
<div ng-repeat="a in flightdetails ">
<div ng-repeat="b in a.booking">
<div ng-repeat="c in b.flightdata">
<div ng-repeat="d in c.segments">
{{d.flightnumber}}
</div>
</div>
</div>
</div>
You can use nested ng-repeat to bind your data - see a demo below:
angular.module("app", []).controller("ctrl", function($scope) {
$scope.confirm = {
booking: {
flightData: [{
Segments: [{
FlightNumber: 1
}, {
FlightNumber: 2
}]
}, {
Segments: [{
FlightNumber: 3
}, {
FlightNumber: 4
}]
}]
}
}
// console.log($scope.confirm);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="wrapper" ng-app="app" ng-controller="ctrl">
<div ng-repeat="x in confirm.booking.flightData">
Data {{$index + 1}}:
<div ng-repeat="y in x.Segments">
<div>Flight No: {{y.FlightNumber}}</div>
</div>
<br/>
</div>
</div>
If you want to display only the following:
confirm.booking.flightData[0].Segments[0].FlightNumber
confirm.booking.flightData[0].Segments[1].FlightNumber
confirm.booking.flightData[0].Segments[2].FlightNumber
then you can use limitTo - see demo below:
angular.module("app", []).controller("ctrl", function($scope) {
$scope.confirm = {
booking: {
flightData: [{
Segments: [{
FlightNumber: 1
}, {
FlightNumber: 2
}]
}, {
Segments: [{
FlightNumber: 3
}, {
FlightNumber: 4
}]
}]
}
}
// console.log($scope.confirm);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="wrapper" ng-app="app" ng-controller="ctrl">
<div ng-repeat="x in confirm.booking.flightData | limitTo : 1">
Data {{$index + 1}}:
<div ng-repeat="y in x.Segments">
<div>Flight No: {{y.FlightNumber}}</div>
</div>
<br/>
</div>
</div>
I created an example here:
http://codepen.io/ackzell/pen/ENBymo
It ultimately looks like this, but check the pen as it has some more info:
<ul>
<li ng-repeat="flight in vm.flightData">
<ul>
<li ng-repeat="segment in flight.Segments">
<em>FlightNumber</em> {{ segment.FlightNumber }}
<br />
<em>Departure:</em> {{ segment.DepartureAirport }}
<br />
<em>Arrival:</em> {{ segment.ArrivalAirport }}
</li>
</ul>
</li>
</ul>
Nesting ng-repeats would help, but maybe you want to give your data some treatment first.
I was doing a very quick exercise with angular directives. My code is very simple.
app.js:
var app = angular.module('readingList', []);
app.controller('BooksController', function($scope){
$scope.books = books;
$scope.genres = genres;
})
app.directive('bookGenres', function(){
return {
restrict: 'E',
templateURL: 'partials/book-genres.html'
};
});
var books = [{
title: 'ABCD',
author: 'E. Fgh',
isbn: '123414312341234',
review: 'Hello world',
rating: 4,
genres: {
'non-fiction': true, fantasy: false
}
}];
var genres = ["foo1","bar2","foo2","bar3"];
}
app.html:
<div class="row" ng-controller="BooksController">
<button class="btn btn-default">Create Review</button>
<hr />
<hr />
<ul class="list-unstyled col-sm-8" >
<li class="book row" ng-repeat="book in books">
<aside class="col-sm-3">
<a href="http://www.amazon.com/gp/product/{{book.isbn}}">
<img ng-src="http://images.amazon.com/images/P/{{book.isbn}}.01.ZTZZZZZZ.jpg" alt="" class="full"/>
</a>
<p class="goodRating rating">{{book.rating}}/5</p>
</aside>
<div class="col-sm-9 col-md-8">
<h3>
<a href="https://rads.stackoverflow.com/amzn/click/com/0553593714" rel="nofollow noreferrer">
{{book.title}}
</a>
</h3>
<cite class="text-muted">{{book.author}}</cite>
<p>{{book.review}}</p>
<!-- Put Genre Here -->
<book-genres></book-genres>
<ul class="list-unstyled">
<li ng-repeat="(genre, state) in book.genres">
<span class="label label-primary" ng-show="state === true">
{{genre}}
</span>
</li>
</ul>
</div>
</li>
</ul>
</div>
book-genres.html:
<ul class="list-unstyled">
<li ng-repeat="(genre, state) in book.genres">
<span class="label label-primary" ng-show="state === true">
{{genre}}
</span>
</li>
</ul>
Everything renders with the view except my book-genres directive. For reason, it doesn't work. I have checked the documentation. I checked other similar examples and nothing. If I can't get this directive to work, rendering out the other components such as the image is going to be a problem. I also checked the path of the partials views as well.
There's a couple possibilities here. You need to be sure to inject $scope into your controller:
app.controller('BooksController', ['$scope', function($scope) {
// do stuff
}]);
book.genres is not defined anywhere, so your ng-repeat has no items to display.
templateURL is also incorrect, it should be templateUrl.
I have a Json data like this
Object {Science: Array[3], Accounts: Array[3], History: Array[3], Mathematics: Array[3]}
Accounts: Array[3]
0: Object
1: Object
2: Object
length: 3
History: Array[3]
Mathematics: Array[3]
Science: Array[3]
Now to render this data in HTML page like this
<h1> Accounts</h1>
<div> Object </div>
<div> Object </div>
..................
You can use ng-repeat directive with JSON Data like this example:
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<div data-ng-app="" data-ng-init="names=['Jani','Hege','Kai']">
<p>Looping with ng-repeat:</p>
<ul>
<li data-ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
Fiddle Demo With Array
And You can even show your nested objects using ng-repeat directive like this:
<ul ng:controller="Cntl">
<li ng:repeat="item in data">
{{item.name}} has children:
<ul>
<li ng:repeat="child in item.children">{{child.name}} has grant-children:
<ul><li ng:repeat="gch in child.children">{{gch.name}}</li></ul>
</li>
</ul>
</li>
</ul>
<script>
function Cntl() {
this.data = [{
name: '1',
children: [{
name: '11',
children: [{
name: '111'}, {
name: '112'}]}, {
name: '12',
children: [{
name: '121'}, {
name: '122'}]}]}, {
name: '2',
children: [{
name: '21'}, {
name: '22'}]
}];
}
</script>
Fiddle Demo With Nested Objets
Got my answer
<div class="panel" ng-repeat="(subject, activities) in Activities">
<h3 class="panel-title followMeBar">{{subject}}</h3>
<div class="panel-body">
<ul class="list-group">
<div class="row list-group-item" ng-repeat="activity in activities">
<div class="col-xs-4">
<img class="scale-notebook-image" src={{activity.fileTypeImg}}>
</div>
<div class="col-xs-8">
<div>{{activity.fileTitle}}</div>
<div>by {{activity.createdBy}}</div>
</div>
</div>
</ul>
</div>
</div>