How to use "OR" in ng-repeat - javascript

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>

Related

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

AngularJs:Strange result in iterating key value pair

I have an array in angular as follows
$scope.arr={
"abc/xyz/../": [
"a1.txt",
"a2.txt",
"a3.txt"
],
"": [
"no-folder.txt"
],
"abc1/xyz/../": [
"a4.txt",
"a5.txt",
"a6.txt"
]
}
i want to iterate through this array and need to get the results as follows
"a1.txt",
"a2.txt",
"a3.txt"
and
"no-folder.txt"
and
"a4.txt",
"a5.txt",
"a6.txt"
i have tried as follows
<div ng-repeat="test in arr track by $index">
<h3 ng-repeat="(key, value) in test">
{{value}}
</h3>
</div>
but i am getting strange results as each character is coming as result .
can u pleas help.
update
please look to this fiddle
https://jsfiddle.net/771voyj6/8/
I don't know what you want to do but you can create your logic something like this it might work for you ,its some hardcoded work but change it accordingly
$scope.test = []
$scope.test.push(arr["abc1/xyz/../"]+arr[""]+arr["abc1/xyz/../"]);
Use test in ng-repeat .. :)
or you can do what i know with your code use ng-repeat like this for your code:
<div ng-repeat="test in arr">
<div ng-repeat="test2 in test">
{{test2}}
</div>
I don't know if Pankaj is right regarding the empty key value. But certainly your $scope.arr is not an array but an object.
As such your code should be:
<div ng-repeat="(key, value)in arr track by $index">
<h3 ng-repeat=" item in value">
{{item}}
</h3>
</div>
I suspect that the JSON you are getting is not valid JSON. In second second property of your object is ""(blank) which would be invalid JSON.
JSON
{
"abc/xyz/../": [
"a1.txt",
"a2.txt",
"a3.txt"
],
//in below line json has no key
"": [
"no-folder.txt"
],
"abc1/xyz/../": [
"a4.txt",
"a5.txt",
"a6.txt"
]
}
Update
Apology for having wrong conceptualization regarding JSON, above JSON is valid JSON (but technically JSON shouldn't have blank key). I tried the above code in Fiddle which is working fine.
Working Fiddle(Angular 1.4.8)
You need to replace your HTML code with the following:
<div ng-repeat="test in arr track by $index">
<div ng-repeat="item in test">
{{item}}
</div>
</div>
I am getting the result. Please check the following JSFiddle:
http://jsfiddle.net/akonchady/a25r1mm4/3/

AngularJS: displaying an array of objects in separate rows

Let's say, I have an array of objects and I want to display it in several rows. Each row should consist of a specific number of objects. Basically, it should look like this:
<div class="row">
<div class="col-md-4">item</div>
<div class="col-md-4">item</div>
<div class="col-md-4">item</div>
</div>
<div class="row">
<div class="col-md-4">item</div>
<div class="col-md-4">item</div>
<div class="col-md-4">item</div>
</div>
...
I've implemented it with a very dirty trick, generating an additional array of numbers and iterating through it (4 is a number of objects in a row):
<div class="row titles-row" ng-repeat="row in outRange(series.length, 4)">
<project-preview class="col-md-3" ng-repeat="project in series" ng-if="$index < (row + 1)*4&& $index >= (row)*4"></project-preview>
</div>
and outRange function:
$scope.outRange = function(items_num, row_width) {
items_num = items_num > 0 ? items_num : 0;
var rows_num = Math.ceil(items_num / row_width);
return Array.apply(null, Array(rows_num)).map(function (_, i) {return i;});
};
It works, but I feel like there should be a better way to do it.
If this is just a matter of presentation, bootstrap (which it seems you might be using) will automatically put the other objects on a separate row when the sum of columns is more than 12 (it uses floats). If however the objects have significantly different sizes, this might not look so good indeed. Still, I would tend to leave this under control of CSS, rather than in javascript.
One approach would be to use a display: flexbox on the container, which should have the effect you want automatically. Lookup this CSS property to discover the true strength of flexbox.
If you really want to do it in javascript, you could have a template like:
<div ng-class='{row: $index % 4 == 0}' ng-repeat='...'>
<div class='col-md-4'>
..
</div>
</div>
This will generate extra divs, but that is likely acceptable.
Instead of outRange, use a filter to create chunks out of the series array. Lodash has a chunk method. Or you can implement one yourself.
Thanks for your ideas. I came up with this solution:
mainApp.filter('slice', function() {
return function(array, row_width, scope) {
if(array == undefined)
return;
if(scope.sliceResult != undefined)
return scope.sliceResult;
scope.sliceResult = [];
var rows_num = Math.ceil(array.length / row_width);
for(var i = 0; i < rows_num; i++) {
scope.sliceResult.push(array.slice(i * row_width, i * row_width + row_width));
}
return scope.sliceResult;
};
});
And here how I use it:
<div class="row titles-row" ng-repeat="row in series | slice: 4 : this">
<project-preview class="col-md-3" ng-repeat="project in row"></project-preview>
</div>
Still I don't like that I need to pass the scope inside the filter.

ng-repeat appending data multiple times

HTML
<div ng-app="templeApp" ng-controller="templeList">
<div ng-repeat="temple in temples track by $index" >
<h2>{{temple.strTempleName}}</h2>
<h4>{{temple.strTempleDescription}}</h4>
<h4>5km from current location</h4>
</div>
</div>
JS
var templeApp = angular.module('templeApp', [])
.controller('templeList',function($scope,$http){
$scope.temples = [{"_id":"new","strTempleName":"Temple 1 Name","strTempleDescription":"Temple 1 description","strContactNumber":"+91899999999","strTempleLocation":"Chennai","iTempleRating":5,"strContactPersonName":"","strTempleCoordinates":""}] ;
$http.get("https://gist.githubusercontent.com/vigneshvdm/d106ea482a792c60dff8/raw/c8f020eb54c4068e40884b8d84c972d92e8e4e08/vicky%20test%20file").success(function(data){
$scope.temples = data[0]; //uncomment this line to see error
console.log(data[0]);
});
});
PROBLEM
When i comment the $scope.temples = data[0]; line, ne-repeat is appending data only once, but when i assign the data to $scope.temples its appending same data multiple time
DEMO LINK
remove track by $index in ng-repeat and change the below like this
in this example i used temple.strTempleName for track by filter make sure it is return unique names.
<div ng-app="templeApp" ng-controller="templeList">
<div ng-repeat="temple in temples track by temple.strTempleName" >
<h2>{{temple.strTempleName}}</h2>
<h4>{{temple.strTempleDescription}}</h4>
<h4>5km from current location</h4>
</div>
</div>

ng-repeat run as many times as integer parameter doesn't work in some cases

I want to run angular as many times as integer value passed to it.
EDIT: I simplified this example because originally I used function to return array based on number passed to it.
HTML
<body ng-app="userFilterModule">
<div class="container-fluid" ng-controller="UserfilterController as Ctrl">
<div class="row">
<div class="filter_tableTbody col-xs-12">
<div class="row filter_tableRow" ng-repeat="user in Ctrl.obj_users">
<!-- ... -->
<div class="col-xs-2">
<span class="filter_rateStars" ng-repeat="a in Ctrl.ratingArr| limitTo: user.rate">
★
</span>
<span class="filter_rateStars notActive" ng-repeat="a in Ctrl.ratingArr| limitTo: 5 - user.rate">
☆
</span>
</div>
</div>
</div>
</div>
</div>
</body>
And everything works fine if ratingArr contains numbers e.g.
app.controller('UserfilterController', function ($scope) {
this.int_male_counter = this.int_female_counter = 5;
this.str_sort_by = {
prop_name: 'f_name',
order: 'asc'
};
//problem starts here
this.ratingArr = [1,2,3,4,5];
this.obj_users = new Users(this.int_male_counter, this.int_female_counter).list;
this.fn_set_sorting = function (str) {
if (this.str_sort_by.prop_name === str) {
this.str_sort_by.order = this.str_sort_by.order === 'des' ? 'asc' : 'des';
} else {
this.str_sort_by.order = 'asc';
this.str_sort_by.prop_name = str;
}
this.obj_users.sortByObjKeyVal(this.str_sort_by.prop_name, this.str_sort_by.order);
};
this.fn_setlected_filter = function (str) {
return str === this.str_sort_by.prop_name;
};
this.fn_is_descending = function(){
return this.str_sort_by.order === 'des';
};
});
But when I change it to new Array(5) or ['','','','',''] or ['a','a','a','a','a']
I get error in console: Error: [ngRepeat:dupes] why?
Thanks!
By default, you cannot use identical values in the array processed by ng-repeat. Quoting the docs:
error:dupes
Duplicate Key in Repeater
Occurs if there are duplicate keys in an ngRepeat expression.
Duplicate keys are banned because AngularJS uses keys to associate DOM
nodes with items.
By default, collections are keyed by reference which is desirable for
most common models but can be problematic for primitive types that are
interned (share references).
As advised in the same docs, just use track by $index suffix (so that items will be keyed by their position in the array instead of their value) to resolve the issue:
<span class="filter_rateStars"
ng-repeat="a in Ctrl.ratingArr | limitTo: user.rate track by $index">

Categories

Resources