Angularjs ng-repeat use key as property name of an obj - javascript

In angular, I would like to use key of a ng-repeat as a property name of an obj
$scope.datas= {};
$scope.datas.key1 = 'val1';
$scope.datas.key2 = 'val2';
$scope.dictionnary= {};
$scope.dictionnary['key1'] ='toto';
$scope.dictionnary['key2'] ='titi';
<div ng-repeat="(key, value) in datas">
{{dictionnary[key]}} //does not work!
</div>
Do you know hot to do this?

Ok so it may come down to a few things:
1:
you can use datas also as a dictionary and then it would work with 1 loop (PICK ME)
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.datas = {};
$scope.datas.key1 = 'val1';
$scope.datas.key2 = 'val2';
$scope.dictionnary = {};
$scope.dictionnary['key1'] = 'toto';
$scope.dictionnary['key2'] = 'titi';
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myController">
<div ng-repeat="(key, value) in datas">
{{dictionnary[key]}} //does not work!
</div>
</div>
</div>
2: you can use nested ng-repeat like #Omri Aharon showed

If you want to do this for all objects you would need 2 ng-repeats here, one to iterate over your array, and the other one to fetch the key from the object you are now iterating on:
<div ng-repeat="data in datas">
<div ng-repeat="(key, value) in data">
{{key}}
</div>
</div>
Note that here you already have the object as data, so if you explained your problem we could suggest maybe a different approach.
Fiddle

Related

watch the value in angularjs

how to watch the array value of ng-model in angularjs i have created fiddle but does not work Please take a look and suggest.
Thanks
<div ng-app ng-controller="ParentCtrl">
<div ng-controller="ChildCtrl">
<table>
<tr ng-repeat="user in profiles track by $index">
<td>
<input
type="text"
name="parktime_{{user.user_id}}"
ng-model="orderItems[user.user_id].parktime"
>
</td>
</tr>
</table>
</div>
</div>
function ParentCtrl($scope) {
}
function ChildCtrl($scope) {
$scope.parkOptions = {};
$scope.profiles = [
{user_id: '01', park_name: 'England Park'},
{user_id: '02', park_name: 'France Park'}
];
$scope.orderItems = {};
$scope.orderItems.parktime = "Test";
$scope.$watch('orderItems[profiles.user_id].parktime', function(newVal, oldVal){
console.log(newVal);
})
}
http://jsfiddle.net/w5vskLfc/59/
I suggest you use ng-change instead. You can't use watch this way, it is to watch a single property instead.
I've also updated your model to use ng-init. This is something you should be careful with using, but in your case, you need to have an key defined at each position of your orderItems object. If you will always statically assign these, I recommend iterating through them once and creating a key that way instead.
HTML
<input type="text" name="parktime_{{user.user_id}}"
ng-init="orderItems[user.user_id] = {}"
ng-model="orderItems[user.user_id].parktime"
ng-change="onChange(user.user_id)">
JS
$scope.onChange = function(items) {
console.log(items);
}
You are trying to access indexes which does not exist. profiles is an array of objects and I don't think there is anything available on profiles.user_id index. Also, I don't think orderItems[profiles.user_id] will work as that index also doesn't exist.

How do I display this json file correctly in ng-repeat?

I'm trying to create a Store page for my website. I want to display the following json file in ng-repeat:
{
"cupcakes": {
"Vanilla": [
{"price":"9.99", "stock":"20", "amount":"8",
"ingredients":"flour, sugar, vanilla extract",
"popular":true}
],
"Maple": [
{"price":"9.99", "stock":"15", "amount":"8",
"ingredients":"flour, sugar, maple syrup",
"popular":true}
]
},
"cookies": {
"Vanilla": [
{"price":"7.99", "stock":"50", "amount":"12", "ingredients":"flour, sugar, vanilla extract"}
],
"Maple": [
{"price":"7.99", "stock":"50", "amount":"12", "ingredients":"flour, sugar, maple syrup"}
]
}
}
I want to display the type item (cupcake or cookie) then the type of each item (vanilla or maple) then the unique attributes and be able to filter and search through them. I'm thinking I may have to restructure my json file, but I'm not sure. Should I sort out the items ahead of time in my controller with a forEach? Here is my controller:
angular.module('root', [])
.controller("index", ['$scope', '$http', function ($scope, $http) {
$scope.name = null;
$scope.email = null;
$scope.comments = null;
$scope.reason = null;
$scope.employees = [];
$scope.items = [];
$http.get('http://localhost:8000/employees.json').then(function(result) {
$scope.employees = result.data.records;
});
$http.get('http://localhost:8000/inventory.json').then(function(result) {
$scope.items = result.data;
});
$scope.isEnabled = function() {
if ($scope.name && $scope.email && $scope.comments) {
return false;
}
else {
return true;
}
}
}])
In Javascript, almost everything is an array. You can iterate over an array of objects or, in an object you are iterating over his properties.
The following script should do the work.
<div ng-repeat="(itemLabel, itemValue)in items">
{{itemLabel}}
<div ng-repeat="(flavorLabel, flavorValue)in itemValue">
{{flavorLabel}}
<div ng-repeat="object in flavorValue">
<div ng-repeat="property in object">
{{property}}
</div>
</div>
</div>
</div>
jsfiddle
Here is a way for showing your data using ng-repeat:
<div ng-repeat="(foodKey, foodVal) in foods">
<b>{{foodKey}}</b>
<div ng-repeat="(typesKey, typesVal) in foodVal">
<span>{{typesKey}}</span>
<ul ng-repeat="types in typesVal">
<li ng-repeat="(key, val) in types">
{{key}} : {{val}}
</li>
</ul>
</div>
</div>
Of course it will only work if foods is the json you posted in your answer.
Here is a working jsFiddle.
For more information on ng-repeat see here.
Just going through your JSON.
<div ng-repeat="(key, value) in inventory">{{key}}
<ul>
<li ng-repeat="(material_key, material_value) in value">{{material_key}}
<ul>
<li ng-repeat="(options_key, options_value) in material_value[0]">{{options_key}} - {{options_value}}</li>
</ul>
</li>
</ul>
<br>
Have a look at this plunker. I hope this will solve you problem.
you need multiple ng-repeaters hope this plunker is your requirement
you can do anything with the keys of your JSON in javascript , by converting the JSON to object by
JSON.parse(json);
later on you can access any key and that will be an object/hashmap to loop or sort
So in your case, your API result can be parsed like
var resultData = JSON.parse(result.data);
Later you can do ng-repeat in your view some thing like
[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'

ng-if condition with key value - Angular js

I'm testing a webapp using angularjs, my app.js is reading a JSON file and gets some data:
var category = document.getElementById('category').value;
var App = angular.module('App', []);
App.controller('control', function($scope, $http){
$http.get('../../zz-dashboard/motores/datatodo/INFO/filtros/'+category+'.json')
.then(function(res){
$scope.items = res.data;
});
});
I would like to show the data conditioned in the key or val value, using ng-if. For example, in this case if the key of my array is equal to "sleeves" I would like to show the value, only in that case.
<p ng-repeat="(key, val) in items" ng-if="key=='sleeves'">
{{key}} - {{val}}
</p>
I'm new in angularjs and I didn't found a clear answer to my question, I would apreciate any help.
Just Try
<p ng-repeat="item in items track by $index" ng-show="$index == 'sleeves'">
{{$index}} - {{item}}
</p>

AngularJS : After ng-repeat $scope values not updated as expected

I have a controller that contains data to be iterated over with an ng-repeat, and I'm using it alongside this selection model directive.
After using ng-repeat to create several entries in the DOM, the bindings to $scope.selectedItems stop working.
I know ng-repeat create a new child scope for each iteration, but shouldn't the updates to the selectedItems property still be picked up by binding to values in the MyController?
Controller:
(function() {
angular.module('myModule', ['product.module'])
.controller('MyController' ['$scope', 'SomeService' function($scope, ProductService) {
$scope.selectedItems = [];
$scope.productService = new ProductService() //constructor pattern object
$scope.products = $scope.productService.items;
$scope.productService.fetchData(); //grabs data from server and sets the productService.items to an array of objects
}]);
})();
HTML
<div ng-controller="MyController">
<ul>
<li ng-repeat="product in products"
selection-model-type="checkbox"
selection-model-mode="multiple"
selection-model-selected-items="selectedItems">
{{product.name}}
</li>
</ul>
<div ng-controller="MyController"> <!-- this binding doesn't work after the ng-repeat takes place -->
There are {{selectedItems.length}} products
</div>
productService.items may refer to the same instance all the time but selectedItems surely not. Use only one controller or place selectedItems into a service.
<div ng-controller="MyController">
<ul>
<li ng-repeat="product in products"
selection-model-type="checkbox"
selection-model-mode="multiple"
selection-model-selected-items="selectedItems">
{{product.name}}
</li>
</ul>
There are {{selectedItems.length}} products
</div>

How to use "OR" in ng-repeat

I have different response in different scopes and I need to check in both the scopes for the values in ng-repeat.
For Example:
$scope.abc = data;
$scope.def = data;
<div ng-repeat = result in abc || mresult in def></div>
But the ng-repeat is failing may be OR is not working, is there any way to handle this.
<div ng-repeat="result in abc || def">
You should either have 2 ngRepeats:
<div ng-repeat="result in abc"></div>
<div ng-repeat="result in def"></div>
Or concatenate the arrays:
<div ng-repeat="result in abc.concat(def)"></div>

Categories

Resources