<div ng-repeat="widget in widgets"
ng-class="">
<div>{{widget.row}}</div>
</div>
I'm trying to apply a class inside the repeat based on a particular value in the repeat, for example if widget.row = 0 and it is the first widget with that value displayed then give it a class and all the other widgets that have row as 0 do not get the class. This will need to be the case if it equals 1 or 2 and so on so I can't just use $first as there will be multiple row values and multiple widgets for example it may output something like:
0 0 0 0 1 1 2 2 2 2
So the easiest way for me to achieve this was using the Adjacent sibling selector rather than do it with angular as each item is not really aware of the others:
<div ng-repeat="widget in widgets"
class="widget-row-{{widget.row}}">
<div>{{widget}}</div>
</div>
and then use CSS for:
.widget-row-0:first-child {}
.widget-row-0 + .widget-row-1 {}
.widget-row-1 + .widget-row-2 {}
.widget-row-2 + .widget-row-3 {}
Best practise is to prepare your data in a init function in your controller. It's nice and KISS! It's the best way to prepare your data in control function instead of misapply the E2E binding of AngularJS. It solve your problem so no class is written when there is no need for (as you asked for). Its proceeded once instead of calling a function again, again and again by E2E binding like ng-class="shouldIAddAClass()".
View
<div ng-repeat="widget in widgets"
ng-class="{ 'first' : widget.first }">
<div>{{widget.row}}</div>
</div>
Controller
$scope.widgets = [{
row: 0
}, {
row: 2
},{
row: 0
},{
row: 1
},{
row: 1
},{
row: 2
},{
row: 0
}];
//self calling init function
(function init () {
var widgetRowFound = {};
angular.forEach($scope.widgets, function (widget, key) {
if (angular.isDefined(widgetRowFound[widget.row])) {
$scope.widgets[key].first = false;
} else {
$scope.widgets[key].first = true;
widgetRowFound[widget.row] = true;
}
});
})();
Not the cleanest one but will work
<div ng-repeat="widget in widgets">
<div ng-class="{'myClass': applyClass(0, widget.row)}"></div>
</div>
----------
$scope.widgetsRows = {};
function applyClass(number, row){
if(!$scope.widgetsRows[row]){
$scope.widgetsRows[row] = true
}
return row == number && $scope.widgetsRows[row];
}
You can add the class you want to use to the widget objects in the controller first:
var tempRow = "";
for(var i = 0;i < $scope.widgets.length;i++) {
if($scope.widgets[i].row != tempRow) {
$scope.widgets[i].class = "myClass";
tempRow = $scope.widgets[i].row;
}
}
Then you can use that class:
<div id="widgets" ng-repeat="widget in widgets"
class="{{widget.class}}">
<div>{{widget.row}}</div>
</div>
Hope this helps
You can create a method that will be called from ng-class to achieve your goal. The method should return the class to be used.
$scope.firstHitFound = false;
$scope.isFirstZeroValue = function(value){
if($scope.firstHitFound == false && value == 0){
$scope.firstHitFound = true;
return class1;
}else{
return class2;
}
}
The HTML / Angular shoudl look as:
<div ng-class="isFirstZeroValue(widget.row)">
If you want to style it, add the class to all the widget that match your criteria, and use css to perform it only on the first of them.
Html:
<div id="widgets" ng-repeat="widget in widgets"
ng-class="{'widget-first': widget.row == 0}">
<div>{{widget.row}}</div>
</div>
Css:
#widgets.widget-first:first-of-type {
background: #ff0000;
}
You can use ng-class in addition of your ng-repeat:
Example
<div ng-repeat="widget in widgets" ng-class="{'test': widget.value === 0}">
<div>{{widget.row}}</div>
</div>
You need to call a method that will check if the row result is not same with previous value. If it not same , it will return true value and will be assigned ng-class, and if not return false. Filter this out using ng-if.
Html
<div ng-repeat="widget in widgets"
ng-class="">
<div ng-if="calculate(widget.row)">
<div ng-class="test">{{widget.row}}</div>
</div>
<div ng-if="!calculate(widget.row)">
<div>{{widget.row}}</div>
</div>
</div>
Controller
var arr = [];
$scope.calculate = function (row) {
arr.push(row);
var breakLoop = false;
angular.forEach(arr, function (oldVal, newVal) {
breakLoop = false;
if (oldVal != newVal) {
breakLoop = true;
}
)};
return breakLoop;
}
Related
Hi I have been using this tag to change my css style, if the condition totalAsset and sortedAsset are same
<div class="table-row" ng-repeat="x in myData"
ng-model="sort(x.totalAsset)"
ng-class="{'lightblue': x.totalAsset == sortedAsset}">
totalAsset is my data in like this
$scope.myData = [
{
totalAsset: "23557"
},
{
totalAsset: "4512190",
},
{
totalAsset: "2190",
},
{
totalAsset: "1256790",
}
]
i have create a function that self sort the totalAsset
$scope.sort = function(totalAsset) {
$scope.unsortedAsset = totalAsset;
$scope.sortedAsset = $scope.unsortedAsset.split("").sort().join("");
console.log(sortedAsset);
}
in the logic only the first and last row will become blue the other two rows remain same.
But my problem here is only the last one become blue, the first one doesn't.
I am not sure about, if you need the {{ }}( they are not needed in ng2 atleast ).
<div class="table-row" ng-repeat="x in myData"
ng-model="sort(x.totalAsset)"
ng-class="x.totalAsset == sortedAsset ? 'lightblue' : ''">
Second approach is to do the if in controllers function
$scope.areValuesEqual() {
if($scope.x.totalAssets == $scope.sortedAssets) {
return 'lightblue';
}
return;
}
But this looks rather ugly, but i am just throwing this out there.
I am trying to create a switch based on a dynamic array of objects...
For example:
<div ng-switch on="currentItem">
<div ng-repeat="item in myItems" ng-switch-when="item.name">
<p>{{item.name}}</p>
<button ng-click="nextItem(item)">Next Item</button>
</div>
</div>
And then in my controller...
$scope.myItems = [{
"name": "one"
}, {
"name": "two"
}]
// Default first item
$scope.currentItem = $scope.myItems[0].name;
$scope.nextItem = function(med) {
for (var i = 0; i < $scope.myItems.length; i++) {
if ($scope.currentItem === $scope.myItems[i].name) {
if ($scope.myItems[i + 1] !== undefined) {
$scope.currentItem = $scope.myItems[i + 1].name
}
}
}
}
Basically, the dom should render a div for each of the items, and when a user clicks the Next Item button, currentItem should be updated, and the switch should trigger based on that.
I am not seeing the first result as I should (nothing is being rendered). Any help would be greatly appreciated.
Plunk: http://plnkr.co/edit/PF9nncd1cJUNAjuAWK22?p=preview
I have forked your plunkr: http://plnkr.co/edit/A9BPFAVRSHuWlmbV7HtP?p=preview
Basically you where not using ngSwitch in a good way.
Just use ngIf:
<div ng-repeat="item in myItems">
<div ng-if="currentItem == item.name">
<p>{{item.name}}</p>
<button ng-click="nextItem(item)">Next Item</button>
</div>
</div>
I've forked your plunkr: http://plnkr.co/edit/2doEyvdiFrV74UXqAPZu?p=preview
Similar to Ignacio Villaverde, but I updated the way your getting the nextItem().
$scope.nextItem = function() {
var next = $scope.myItems[$scope.myItems.indexOf($scope.currentItem) + 1];
if(next) {
$scope.currentItem = next;
}
}
And you should probably keep a reference in currentItem to the entire object, not just the name:
<div ng-repeat="item in myItems">
<div ng-if="item == currentItem">
<p>{{item.name}}</p>
<button ng-click="nextItem(item)">Next Item</button>
</div>
Much simpler!
Please see this JS fiddle link.
http://jsfiddle.net/4Dpzj/174/
This is the logic for group by
app.filter('groupBy', ['$parse', function ($parse) {
return function (list, group_by) {
var filtered = [];
var prev_item = null;
var group_changed = false;
// this is a new field which is added to each item where we append "_CHANGED"
// to indicate a field change in the list
//was var new_field = group_by + '_CHANGED'; - JB 12/17/2013
var new_field = 'group_by_CHANGED';
// loop through each item in the list
angular.forEach(list, function (item) {
group_changed = false;
// if not the first item
if (prev_item !== null) {
// check if any of the group by field changed
//force group_by into Array
group_by = angular.isArray(group_by) ? group_by : [group_by];
//check each group by parameter
for (var i = 0, len = group_by.length; i < len; i++) {
if ($parse(group_by[i])(prev_item) !== $parse(group_by[i])(item)) {
group_changed = true;
}
}
}// otherwise we have the first item in the list which is new
else {
group_changed = true;
}
// if the group changed, then add a new field to the item
// to indicate this
if (group_changed) {
item[new_field] = true;
} else {
item[new_field] = false;
}
filtered.push(item);
prev_item = item;
});
return filtered;
};
I want to group all the products together.
what changes i need to do ?
I come up with this in my mind. Without using any custom filters.
I simply use this ng-repeat syntax :
ng-repeat="(key,item) in MyList | orderBy:orderKey"
Thanks to it i can get the key to compare the value with the previous object.
Here is my ng-show attribute. It can be improved by sorting the list somewhere else (like in the controller)
<h2 ng-show="(MyList | orderBy:orderKey)[key-1][orderKey] !== (MyList | orderBy:orderKey)[key][orderKey]"
Thanks to this you can populate your var "orderKey" with any of your attribute name and this will works.
See it working in this JSFiddle
Hope it helped.
EDIT :
I think it would be a bit cleaner to use a temporary list to manage the visual order (see it in this JSFiddle):
JS :
$scope.orderList = function(){
$scope.orderedList = $filter('orderBy')($scope.MyList,$scope.orderKey);
}
HTML :
ng-change="orderList()" To trigger the list sort
The cleaner ng-repeat / ng-show
<div ng-repeat="(key,item) in orderedList">
<h2 ng-show="orderedList[key-1][orderKey] !== orderedList[key][orderKey]">{{item[orderKey]}} </h2>
<ul>
<li>{{item.ProductName}}</li>
</ul>
</div>
Have a look at this:
http://jsfiddle.net/4Dpzj/176/
<div ng-repeat="item in MyList | orderBy:['SubCategoryName','BrandName'] | groupBy:['SubCategoryName']" >
<h2 ng-show="item.group_by_CHANGED">{{item.SubCategoryName}} </h2>
<ul>
<li>{{item.ProductName}} --- {{item.BrandName}}</li>
</ul>
</div>
I'm trying to see if angularJs is useful for me to create a team-management application.
The issue I have:
I have a complex ng-class definition, being
ng-class="{'guard': ( guard.checked && day.func.indexOf('guard') != -1) }"
and it will prove to be bigger yet.
I was wondering if there is a way to have basically this:
# pseudocode, needs to be translated to js/angularJs
function getClasses(){
classes = ''
if ('guard' in user.day.func and guardCheckBox == checked){
classes = classes.append(' guard')
}
if ('f2' in user.day.func and f2CheckBox == checked){
classes = classes.append(' f2')
}
....
if ('fx' in user.day.func and fxCheckBox == checked){
classes = classes.append(' fx')
}
return(stripLeadingSpace(classes)
}
any tips on what to search, or any bits of code would be appreciated
a js-fiddle with what I have as of yet can be found here:
http://jsfiddle.net/mTJDh/1/
code from the fiddle for dead links
HTML:
Guard
<!--
this snippet applies the class 'guard' to every cell when the checkbox 'Guard' is checked
-->
<div ng-controller="MyCtrl">
<table ng-repeat="user in users">
<tr>
<td>{{user.name}}</td>
<td ng-repeat="day in user.days" ng-class="{'guard': ( guard.checked && day.func.indexOf('guard') != -1) }">
{{day.number}}
</td>
</tr>
</table>
</div>
JS
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.users = [
{name: 'PEDC',
days : [{number:'1', func:'guard'},
{number:'2', func:'guard'},
{number:'3', func:'guard'},
{number:'4', func:['guard','spoc']}
]
},
{name: 'JOVH',
days : [{number:'1', func:'guard'},
{number:'2', func:'guard'},
{number:'3', func:'spoc'},
{number:'4', func:'guard'}
]
}
];
}
CSS
.pending-delete {
background-color: pink
}
.guard {
border:solid black 1px
}
.spoc {
background-color: pink
}
EDIT:
This is the actual solution I use now:
http://jsfiddle.net/mTJDh/2/
basically:
added functions isGuard, isSpoc and isHoliday to my controller, with the day as an argument
these return true or false based on the json array.
idea gotten from here and https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D
ngClass also accepts methods defined on scope which return a boolean value. So you can do something like this:
<td ng-repeat="day in user.days" ng-class="{ 'guard' : getClass(day) }">
{{day.number}}
</td>
JS
$scope.getClass = function(day){
return $scope.guard.checked && day.func.indexOf('guard') != -1
}
I updated your fiddle:
http://jsfiddle.net/mTJDh/4/
use the ngClass as in the accepted answer:
<td ng-repeat="day in user.days" ng-class="getClasses(day)" day="day">
{{day.number}}
</td>
but this time rewrite the method getClasses to return an array.
the array contains at the end every class you wants for a specific day.
$scope.getClasses = function(day){
var classes = [];
if($scope.spoc && $scope.isSpoc(day)) classes.push("spoc");
if($scope.guard && $scope.isGuard(day)) classes.push("guard");
if($scope.holiday && $scope.isHoliday(day)) classes.push("holiday");
return classes;
}
and if you want a more generic one:
http://jsfiddle.net/mTJDh/5/
define:
var availableClasses = [
"guard",
"spoc",
"holiday"]
and use a loop:
$scope.getClasses = function (day) {
var classes = [];
angular.forEach(availableClasses, function (value) {
if ($scope[value] && day.func.indexOf(value) != -1) classes.push(value);
});
return classes;
}
I would use a directive, it was a bit hard to tell from your example which scope variables your CSS rules rely on (and what exactly the rules are), but hopefully it's enough to get started.
.directive('guardClass', [function() {
return {
restrict: 'A',
scope: {
guard: '=',
user: '='
},
link: function(scope, element, attrs, controller) {
scope.$watch(function() {
//return enough info about scope.guard and scope.user
//to know when one has changed
return ...
}, function() {
var classes = [];
if (...) {
classes.push('guard');
}
if (...) {
classes.push('f2');
}
....
if (...) {
classes.push('fx');
}
element.attr('class', classes.join(' '));
});
}
};
}])
And then in HTML
<td guard-class guard="guard" user="user" />
You feed the directive the two (or more) objects it needs to calculate the CSS classes. The directive sets up a $watch to trigger whenever whatever properties on those objects change. It then finds all CSS classes that needs to be there and puts them on the element using angular element.
This saves you from cluttering up your controller with this logic, and it saves you from having extensive amounts of logic inside your templates.
In my application i have 2 array of object.layout array is for creating twitter bootstrap layout.this array is like below :
$scope.layout = [
{c:[{size:12}]},
{c:[{size:2},{size:3},{size:4},{size:3}]},
{c:[{size:3},{size:5},{size:4}]}
];
you can see how this array work in this jsbin.the other array is items array and this array is like below:
$scope.items =[
{row:1,column:0,names:['Jack','Daniel']},
{row:3,column:3,names:['Eli','Bill']},
{row:2,column:1,names:['Fred','David']}
];
and this is the repeater that i used :
<div ng-repeat="(ri,r) in layout" class="row">
<div ng-repeat="(ci,c) in r.c" class="col-md-{{c.size}} col-sm-{{c.size}} col-xs-{{c.size}} col-lg-{{c.size}} bi"> Row{{ri}}-Column{{ci}}
//Maybe other repeater come here
</div>
</div>
now i want when i want to display Jack , Daniel in row 1 column 0 and this 1 and 0 is r and c in repeater of first and second repeater.so when the repeater create row 2 column 1 also repeat on $scop.item and find the related names. but i don't know how to find items in $scope.item.and this is my jsbin
You can do something like this:
<div ng-repeat="(ri,r) in layout" class="row">
<div ng-repeat="(ci,c) in r.c" class="col-md-{{c.size}} col-sm-{{c.size}} col-xs-{{c.size}} col-lg-{{c.size}} bi">
{{getNames(ri, ci)}}
</div>
</div>
Where getNames is defined in controller:
$scope.getNames = function(r, c) {
var items = $scope.items;
for (var i = 0; i < items.length; i++) {
if (items[i].row == r && items[i].column == c) {
return items[i].names;
}
}
return '';
};
Demo: http://jsbin.com/sumuwigo/1/edit