ng-if condition with key value - Angular js - javascript

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>

Related

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'

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

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

ng-repeat is not binding values into Dom?

I am loading data dynamically to ng-repeat so once i receive data its not binding it to ul , i know sometime it happens if you have duplicate indexes but in below case i am not sure what is happening, Any idea ?
main.html
<div>
<ul ng-repeat="message in data track by index">
<li>{{message}}</li>
</ul>
</div>
ctrl.js
angular.module('loggingApp').controller('DitCtrl',function ($scope,DitFactory) {
'use strict';
DitFactory.getLogs().then(function (response) {
$scope.data = response.data;
console.log($scope.data);
});
});
console.log
printing data in console
["test.txt", "test1.txt", "test2.txt", "test3.txt", "test4.txt"]
Your ng-repeat needs to look like this:
ng-repeat="message in data track by $index"

AngularJs - binding passed in paramter to object from different controller

I'm having difficulties in solving this. What I'm trying to achieve is to update iterated objects which is passed in to a function in a different controller.
Here is my controllers -
angular.module('eatmapp.controllers', ['eatmapp.services'])
.controller('AppCtrl', function($scope) {
$scope.intoCart = function(item) {
if(item.type == 'variations'){
item = newItemObj;
}
}
})
.controller('BrowseCtrl', function($scope, dataService, $localstorage) {
dataService.getItems().then(function(returnData) {
$scope.items = returnData.products;
})
});
Here is my view -
<div ng-controller="BrowseCtrl">
<div class="list card product" ng-repeat="item in items" ng-click="intoCart(item)">
<div class="item item-text-wrap">
<span class="ifs-productcat" ng-repeat="category in item.categories">{{category}}<span ng-if="$index != item.categories.length - 1">,</span></span><br>
<h3>{{item.title}}</h3>
<h3>Rs.{{item.price}}</h3>
</div>
</div>
</div>
I need to update item object with newItemObject in iteration(ng-repeat) implemeted in template view after doing some condition check with method (intoCart) in another controller(AppCtrl). I'm fairly new to javascript programming and I'm looking for some help.
The problem I had was not able to get access to 'ng-repeat' child scope in controller.
I solved this using 'this.item' in controller rather than passing the whole object or index.
HTML -
<div class="list card product" ng-repeat="item in items" ng-click="intoCart()"></div>
Controller -
angular.module('eatmapp.controllers', ['eatmapp.services'])
.controller('AppCtrl', function($scope) {
$scope.intoCart = function() {
item = this.item; // current (ng-click) child scope of ng-repeat
if(item.type == 'variations'){
item = newItemObj;
}
}
})
Now, whenever I made changes to 'item' object, it automatically updates scope in view (ng-repeat).
Once way I like to handle this is by using services as setters and getters. The problem is you have to include the service with every controller that needs to access it, but if you don't have too many it's no big deal. So something like this:
.service('userFirstName', function() {
var userFirstNameProp;
return {
getter: function() {
return userFirstNameProp;
},
setter: function(value) {
userFirstNameProp = value;
}
};
})
Then you can call userFirstName.getter() or userFirstName.setter("John") as appropriate.

Cannot render raw HTML using ng-repeat and ng-bind-html

I need have raw html which should be inserted to view as is.
<table>
<tr ng-repeat="el in tableRowsHTML track by $index" ng-bind-html="el">
{{el}}
</tr>
</table>
app.controller('Controller', function ($scope, promiseTemplateObj, $sce) {
$scope.tableRowsHTML = [];
$scope.generateTableRows = function(){ ....};
$sce();
$sce.trustAsHtml($scope.tableRowsHTML[1]);
$sce.trustAsHtml($scope.tableRowsHTML[2]);
$sce.trustAsHtml($scope.tableRowsHTML[3]);
How to fix it?
UPDATE:
I get it partially working with ui-router but problem persists.
<tr ng-repeat="el in tableRowsHTML track by $index" ng-bind-html="el | toTrusted"></tr>
Filter (just for example):
appRoot.filter('toTrusted', ['$sce', function ($sce) {
return function (text) {
return text ? $sce.trustAsHtml(text.replace(/\\n/g, '<br/>')) : '';
};
}]);
Where appRoot - your application.
Update: example http://jsfiddle.net/c5j92821/
You can have a look for ng-sanitize as well. This will help you in binding html from controller to the body. And have a look on this page for few of the examples

Categories

Resources