ng-repeat on objects to create drop down - angularjs

My object looks like:
var models = {
"Test1":{
"name":"Test1",
"members":
{
"T1":{//some more properties},
"T2":{//some more properties}
}
}
"Test2":{
"name":"Test2",
"members":
{
"T1":{//some more properties},
"T2":{//somemore properties}
}
}
}
Provided, user selects a property of object models, I want to display the members property of that selected property of models object in a drop down.
Eg. if user selects Test1 property, drop down should be populated with T1 and T2.
Any suggestions regarding question clarity are appreciated.

As you can't change your object, in your HTML you can have:
<div ng-repeat="model in models">
<div>
<p ng-click="toggleVisibility(model.name)">Name: {{model.name}}</p>
<div ng-repeat="member in model.members" ng-if="model.visibility">
<p>Member Name: {{getMemberName(model.name, $index)}} </p>
<p>Member properties: {{getMemberProperties(model.name, $index)}} </p>
</div>
</div>
</div>
And on your AngularJS Controller:
$scope.toggleVisibility = function (entry) {
$scope.models[entry].visibility = !$scope.models[entry].visibility;
};
$scope.getMemberName = function (entry, $index) {
return Object.keys($scope.models[entry].members)[$index];
};
$scope.getMemberProperties = function (entry, $index) {
var key = Object.keys($scope.models[entry].members)[$index];
return $scope.models[entry].members[key];
};
EDIT: Change the answer to fit the requirements.

Related

Angular cloned array gets changed automatically

I want to have a filter based on active-states from available checkboxes.
First everything should gets displayed, after a filter is selected, in this case a selection of hero names should only display heroes which contains atleast the name.
The interesting part is that: If I try to change the value back to the "full"-object it is not taking the complete object but an altered version of that.
I do not know what is happening there. Because I only initialized the full-object in the constructor of the app. With full-object I mean fullHeroes.
App.Component.ts :
import { Component, OnInit } from '#angular/core';
interface Hero {
name: string;
}
#Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
readonly fullHeroes: Hero[] = [];
heroes: Hero[] = [];
constructor() {
this.heroes.push(
{ name: 'Bob' }, { name: 'Alice' }, { name: 'Mallory' }
);
this.fullHeroes = this.heroes.slice(0);
}
filter(name, checked) {
if (checked) {
for (let i = 0; i <= this.heroes.length; i++) {
let found = false;
const currentHero = this.heroes[i];
if (currentHero && currentHero.name === name) {
found = true;
}
if (found) {
this.heroes.splice(i, 1);
}
}
} else {
this.heroes = [];
this.heroes = this.fullHeroes;
}
return;
}
}
App.component.html :
<div class="container">
<h1>World of Heroes</h1>
<p>Filter your Heroes based on names!</p>
<div class="filter">
<form #heroForm="ngForm">
<fieldset>
<legend>Choose the names</legend>
<div class="form-check" *ngFor="let hero of heroes">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" [name]="hero.name" (change)="filter($event.target.name, $event.target.checked)"> {{hero.name}}
</label>
</div>
</fieldset>
</form>
</div>
<hr>
<h2>Results:</h2>
<div class="row result-list">
<div class="col-md-4 hero" *ngFor="let hero of heroes">
<h3>Name: {{hero.name}}</h3>
</div>
</div>
</div>
If you want to make a clone for the array this.fullHeroes into the array this.heroes, use:
this.heroes = JSON.parse(JSON.stringify(this.fullHeroes));
This way you will do a full copy of the array this.fullHeroes into this.heroes one, and then changes in this.heroes will not affect the other array.
this.heroes = this.fullHeroes
After you execute that line, every time you mutate heroes, you also mutate fullHeroes, since they both refer to the same array. You need to make a copy of fullHeroes.
Note that you're abusing map() where you should be using forEach(). And you're using a loop where you could use some().
You can use the TypeScript spread operator to clone the array:
const a1 = [1, 2, 3, 4, 5, 6];
const a2 = [...a1];

How to apply dynamic filters in AngularJS

I'm starting to learn AngularJS now and I have some issues with filters.
I need to apply two types of filters and I can't figure out how.
I have a device list JSON that looks like this:
[{
"ID": 1,
"Name": "Device 1",
"Price": 1998.92,
"Colors": [{
"ColorCode": "Red",
"ColorName": "#FF0000"
},
{
"ColorCode": "Green",
"ColorName": "#2EFE2E"
}],
"Type": {
"TypeID": 1,
"TypeName": "Mobile device"
},
"Company": {
"CompanyID": 1,
"CompanyName": "Alcatel"
}
}]
I display the list like this:
<div ng-repeat="device in devices | filter:companyFilters | filter:colorFilters">
<span>{{device.Company.CompanyID}}</span> // 1
<span>{{device.Company.CompanyName}}</span> // Google
<span>{{device.Name}}</span> // Nexus 6P
</div>
I have some filters that I applied but there are two filters that I can't understand how to apply.
Filter 1:
A checkbox list of companies that filters the items by the selected
companies.
Filter 2:
A color filter that when clicking on a color will filter the devices
that has that color
For the company filter I have this checkbox list:
<div ng-repeat="company in deviceCompanies">
<input type="checkbox" data-ng-model="companyFilters" id="{{company.CompanyID}}" data-ng-true-value='{{company.CompanyID}}' data-ng-false-value='' />
<label for="{{company.CompanyID}}">{{company.CompanyName}}</label>
</div>
And on the controller side I have this:
$scope.companyFilters = [];
For the color filter I have this:
<div>
<a ng-click="???">All</a>
<div ng-repeat="color in deviceColors" style="display:inline-block; margin-right:10px;">
<div style="width:20px;height:20px;background-color:{{color.ColorCode}}"></div>
<a ng-model="selColor" data-ng="color.ColorCode" ng-click="colorFilters">{{color.ColorName}}</a>
</div>
</div>
And on the controller:
$scope.colorFilters = function (device) {
if (!$scope.selColor)
return true;
for (var i = 0; i < device.Colors.length; i++) {
if (device.Colors[i].ColorCode == $scope.selColor)
return true;
}
return false;
};
But it doesn't work...
Can anyone please tell me how to apply these filters ?
Since you are using ng-repeat which creates its own scope, anything you do in ng-repeat will not get recognized on the controller scope. Using a tool like ng-inspector or batarang will illustrate this.
I recommend using controllerAs Syntax, in your controller add.
angular.module('myModule').controller('CustomFilterController', function() {
var vm = this;
this.devices = //your list of data
this.companyFilters = [];
this.colorFilters = //your function
}
On your view declare your controller like this:
<div ng-controller='CustomFilterController as custom'>
(Note the value after as can be whatever you want it to be)
Then reference anything on that controller as custom.ThingOnController
EX:
<div ng-repeat="device in custom.devices | filter:custom.companyFilters | filter:custom.colorFilters">
After trying some workarounds, this is what I came up with:
<div ng-repeat="company in deviceCompanies">
<!--the ng-click will call a function that updated an array of values-->
<input type="checkbox" id="{{company.CompanyID}}" ng-click="selectCompany(company.CompanyID)">
<label for="{{company.CompanyID}}">{{company.CompanyName}}</label>
</div>
And the controller part is so simple:
$scope.selectedCompanies = [];
//when the array is upted the filter function will also launch
$scope.selectCompany = function (companyId) {
var i = $.inArray(companyId, $scope.selectedCompanies);
if (i > -1) {
$scope.selectedCompanies.splice(i, 1);
} else {
$scope.selectedCompanies.push(companyId);
}
}
$scope.companyFilter = function (device) {
if ($scope.selectedCompanies.length > 0) {
if ($.inArray(device.Company.CompanyID, $scope.selectedCompanies) < 0)
return;
}
return device;
}
Same goes to the colors filter:
<div>
<a ng-click="selectColor()">All</a>
<div ng-repeat="color in deviceColors" style="display:inline-block; margin-right:10px;">
<div style="width:20px;height:20px;background-color:{{color.ColorCode}}"></div>
<a ng-click="selectColor(color.ColorCode)">{{color.ColorName}}</a>
</div>
</div>
And controller part:
$scope.selectedColor;
$scope.selectColor = function (colorCode) {
$scope.selectedColor = colorCode;
}
$scope.colorFilters = function (device) {
if (!$scope.selectedColor)
return true;
for (var i = 0; i < device.Colors.length; i++) {
if (device.Colors[i].ColorCode == $scope.selectedColor)
return true;
}
return false;
};
And finally, applying the filters:
<div ng-repeat="device in devices | filter:companyFilter | filter:colorFilters">
...
</div>
You can have a look here to see how it works
I think the color filter can be more elegant, but, for now, this does the trick.
If I'll come up with a better solution I'll post it here.

Equal Arrays AngularJS Pro

I need to show object only if one of it's properties equals to array.
I have a controller in app.js:
app.controller('checkBoxController', function ($scope) {
$scope.ingredients= [
{label: 'Egg', value: 1},
{label: 'Milk', value: 2},
$scope.selection=[];
$scope.toggleSelection = function toggleSelection(ingredientLabel) {
var idx = $scope.selection.indexOf(ingredientLabel);
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
else {
$scope.selection.push(ingredientLabel);
}
};
});
and an html code for it:
<span style="color:black;" class="selected-item">Selected Items:<span>
<div ng-repeat="label in selection" class="selected-item">
</div>
<div class="list-group">
<div class="list-group-item" ng-repeat="product in meals.products" ng-show="product.contents==selection">
<h1>{{product.name}}</h1>
<meal-gallery></meal-gallery>
<meal-tabs></meal-tabs>
</div>
</div>
And I Have { name: 'Scrambled Egg', contents: "Egg"} in array of products. So I need to show product if it's contents equals to selected ingredients.
I do not have problems when it is only one ingredient like "Egg", but if I need contents of two equal to selected?
It would be best to use a custom filter.
If you add lodash to your application, you can create a filter that will preform a following operation:
angular.module('common', [])
.filter('canBeMadeFrom', function() {
return function(product, ingredients) {
return _.intersection(product.contents, ingredients).length == product.contents.length';
};
});
this will return true if all of products contents are contained in ingredients
use it like this
ng-repeat='product in products | canBeMadeFrom:ingredients'
Use a filter.
<div ng-repeat=product in products |filter: product.a === a && product.b === b>
You can also use a function for filter. It's a function that takes in an item and returns Boolean

How to insert dynamically a text in an object "angular"?

I would like to be able to select a specific object and enter a text in it 'dynamically' in Angular.
App file:
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", ["$scope", function($scope){
$scope.persons = [
{
name: "Kevin",
lastName: "Cris",
mottos : [
{
motto: "Holy Moly!"
}
],
},
{
name: "Tres",
lastName: "Yepo",
mottos : [
{
motto: "Crispy!"
}
],
},
{
name: "Prosi",
lastName: "Nani",
mottos : [
{
motto: "I love this!"
}
],
}
];
}]);
I can insert a text in the object in array[1]:
$scope.addMotto = function(){
$scope.persons[1].mottos.push({
motto: $scope.enterMotto
});
};
But, how could I be able to add motto to a person object each time?
To be more clear: What I am trying to do is: Select a person and add motto.
What I can't figure out is: How to create selection of a person object and add on selected object a text.
Html file:
<div ng-controller="myCtrl">
<section ng-repeat="person in persons">
<p class="header">Persons --</p>
<p>Name: {{person.name}}</p>
<p>lastName: {{person.lastName}}</p>
<p ng-repeat="shoutOut in person.mottos" class="motto">Motto: {{shoutOut.motto}} </p>
</section>
<p ng-repet="newMotto in persons.mottos">Your Motto: {{newMotto.motto}} </p>
<p>Enter Motto:<input type="text" ng-model="enterMotto" /></p>
<button ng-click="addMotto()">Submit </button>
</div><!--myCtrl-->
Live: http://jsfiddle.net/9eau9dq2/
If you want to add to each of the person object, here is what you should do - http://jsfiddle.net/k8o8x60w/
$scope.addMotto = function(){
angular.forEach($scope.persons, function(item, i){
item.mottos.push({motto: $scope.enterMotto});
});
};
If you want to add to the selected person object, you will need to keep the selected id with you and update the id whenever a different person is selected and update his motto accordingly.
You could provide a select box like this to allow user to select a person to which you would want to add a motto
<select>
<option ng-repeat="person in persons" value="{{person.name}}">{{ person.name }} {{ person.lastName }}</option>
</select>
and update your method to...
$scope.addMotto = function () {
angular.forEach($scope.persons, function (item, i) {
if (item.name == $scope.selectedperson) {
item.mottos.push({
motto: $scope.enterMotto
});
}
});
};
Updated fiddle : http://jsfiddle.net/k8o8x60w/1/
Note: Would strongly advice you to use some id too in the person object.
i updated your fiddle with some working code!
http://jsfiddle.net/9eau9dq2/1/
You could also use a select box for sure, but that is really similar anyways ;-)
Hope that helps!
Jan

AngularJS - ng-repeat show one item at a time

looking for some ideas here. i have a meal plan object that contains an array of meals. only one meal can be set as primary at a time but i want the user to be able to cycle through the array of meals and mark a meal as primary. i am stuck trying to figure out if ngrepeat makes sense here or ngswitch or ngshow. any thoughts or samples would be highly appreciated!
I have tried multiple approaches with no luck.
thanks
You could cycle through the meals by index of the meal and have a button to choose the meal like this:
http://jsfiddle.net/c6RZK/
var app = angular.module('mealsApp',[]);
app.controller('MealsCtrl',function($scope) {
$scope.meals = [
{name:'Meatloaf'},
{name:'Tacos'},
{name:'Spaghetti'}
];
$scope.meal_index = 0;
$scope.meal = {};
$scope.next = function() {
if ($scope.meal_index >= $scope.meals.length -1) {
$scope.meal_index = 0;
}
else {
$scope.meal_index ++;
}
};
$scope.choose = function(meal) {
$scope.meal = meal;
}
});
HTML
<div ng-app="mealsApp" ng-controller="MealsCtrl">
<div ng-repeat="m in meals">
<div ng-if="meal_index == $index">
<strong>{{m.name}}</strong>
<button ng-click="choose(m)">Choose</button>
</div>
</div>
<hr>
<button ng-click="next()">Next</button>
<hr>Your Choice: {{meal.name}}
</div>
You could just attach a property to the plan, with a flag that says whether or not it's the primary plan.
Here's a sample implementation:
$scope.plans = [{name:"One"}, {name:"Two"}, {name:"Three"}];
$scope.selectPlan = function(plan) {
for(var i = 0, l = $scope.plans.length; i < l; i++) {
$scope.plans[i].primary = false;
if($scope.plans[i] === plan) {
$scope.plans[i].primary = true;
}
}
};
HTML:
<ul>
<li ng-click="selectPlan(plan)" ng-repeat="plan in plans" ng-class="{primary: plan.primary}"><a href>{{plan.name}}</a></li>
</ul>
If you'd rather not attach properties you could use something like a selected index property on your controller.

Resources