Apply CSS Class With AngularJS Run Time - angularjs

I want to applay css class on that row where MaxStockLevel Is greter than Balence
i had try this code
<tbody ng-repeat="i in products | filter:productFilter">
<!--<tr ng-class="{{i.MaxStockLevel > i.Balence ? 'danger' : 'danger'}} ">-->
<tr class="ng-class : i.maxstocklevel > i.Balence">
<td>{{i.Name}}</td>
<td>{{i.MinStockLevel}}</td>
<td>{{i.MaxStockLevel}}</td>
<td>{{i.Balence}}</td>
</tr>
</tbody>

Your syntax is a bit off:
<tr ng-class="{ 'myCustomClass' : i.maxstocklevel > i.Balence }">
(Also, "Balence" is spelled "Balance")

you should try the following line
<tr ng-class="{ 'YourClassName' : i.maxstocklevel > i.Balance }">
For more info about ng-class click here

ng-class takes a JavaScript object which maps class names to booleans, like so:
var app = angular.module('app', []);
app.controller('Main', function($scope) {
$scope.maxStockLevel = 50;
$scope.items = [];
for (var i = 0; i < 10; ++i)
{
$scope.items.push({ stockLevel: Math.random() * 100 });
}
});
.danger { background: red; }
<div ng-app="app" ng-controller="Main">
<div ng-repeat="i in items" ng-class="{ danger: i.stockLevel > maxStockLevel }">
Item {{ $index }}
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.js"></script>

Related

angular 1.5 orderBy doesn't work

I have an array with objects in it which I would like to sort within my ng-repeat, but no matter which field I get it doesn't seem to respond to anything.
I have the following array:
[{"title":"test 2","planId":"waUVOGARMUyScTYtHI2p_5cAEI_f","dueDate":"","status":0,"assigneePriority":"85868377FP","planTitle":"plan 2","ownerId":"3c9a3683-5057-4e28-b348-0e1f23157bec"},{"title":"Visit the VET","planId":"PyHP00vnzkqxyheVWMOqhZcAFU0F","dueDate":"21-02","status":0,"assigneePriority":"85868377E(","planTitle":"Groep_test23","ownerId":"5cfb5e90-c5d1-4c83-acca-d86e4b912a0c"},{"title":"test","planId":"waUVOGARMUyScTYtHI2p_5cAEI_f","dueDate":"","status":0,"assigneePriority":"85868376\\:","planTitle":"plan 2","ownerId":"3c9a3683-5057-4e28-b348-0e1f23157bec"}]
The controller code:
function getAllTasks() {
datacontext.graph.plannerGetAllTasks().then(function (tasks) {
datacontext.graph.plannerGetAllPlans().then(function (plans) {
var totalTasks = tasks.length;
for (var i = 0; i < totalTasks; i++) {
// append the plan name, owner Id to the tasks object.
var totalPlans = plans.length;
for (var j = 0; j < totalPlans; j++) {
if (plans[j].planId.indexOf(tasks[i].planId) != -1) {
tasks[i].planTitle = plans[j].title;
tasks[i].ownerId = plans[j].ownerId;
}
}
vm.tasks.push(tasks[i]);
}
changeListBucket(vm.currentTab);
});
});
}
and this is my html:
<div class="newsroom-tabs-bottom">
<a class="list-group-item newsItem-pointer" ng-repeat="task in vm.tasksToShow | limitTo: vm.amountOfTasksToShow | orderBy: task.planTitle">
<table style="width: 100%" class="dont-break-out">
<tr>
<td class="planner-icon-set-fixed-width default-text-colour">
{{$index + 1}}
</td>
<td style="width: 100%">
<span>
<span class="list-inbox-info-from-teamnews dont-break-out default-text-colour">{{::task.title}}</span>
</span>
<span class="list-inbox-info-subject dont-break-out default-text-colour">
{{::task.planTitle}}
<span style="float: right">{{ ::task.dueDate }}</span>
</span>
</td>
</tr>
</table>
</a>
</div>
I have checked the following post but none of the solutions worked for me. (Angular - Can't make ng-repeat orderBy work)
any help would be much appreciated. Cheers!
Jus use planTitle
<a class="list-group-item newsItem-pointer" ng-repeat="task in vm.tasksToShow | limitTo: vm.amountOfTasksToShow | orderBy: 'planTitle'">

Give a specific color to even/odd row using angularJS directive no CSS

<table>
<tr ng-repeat="customer in myData"
ng-if="$even" style="background-color: gray">
<td>{{$index+1}}</td>
<td>{{customer.name}}</td>
<td>{{customer.city}}</td>
</tr>
</table>
I got the data from a JSON file and display in view.I need a specific color for even/odd row using angularJS directive. Please help me. Advance thanks.
You could track by $index and determine if the row is odd or even, then set the style based off a ternary operator using the ngStyle style directive.
However, I would recommend using the ngClass directive which would give you better separation between markup and styles, and also make the DOM cleaner.
As an example:
<li ng-repeat="item in tc.list track by $index" ng-class="$index % 2 == 0 ? 'even' : 'odd'">{{item}}</li>
Full Snippet:
var app = angular.module("TestApp",[]);
app.controller("TestController", function() {
var vm = this;
vm.list = [];
function populateDummyItems() {
vm.list.push("One");
vm.list.push("Two");
vm.list.push("Three");
vm.list.push("Four");
}
populateDummyItems();
});
.even {
background-color: lightblue;
}
.odd {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="TestApp">
<h1>Darren's test application!</h1>
<ul ng-controller="TestController as tc">
<li ng-repeat="item in tc.list track by $index" ng-class="$index % 2 == 0 ? 'even' : 'odd'">{{item}}</li>
</ul>
</body>
External Plunker:
https://plnkr.co/edit/4LSB0oKYr0VgSQj0jTxP?p=preview
If you don't want to use css, you can try ng-style
<table>
<tr ng-repeat="customer in myData" ng-style="{'background-color':$even?evenColor:oddColor}">
<td>{{$index+1}}</td>
<td>{{customer.name}}</td>
<td>{{customer.city}}</td>
</tr>
</table>
js
$scope.evenColor = 'yellow'; // you can also enter the hex '#ffff00' here
$scope.oddColor = 'red';
If you don't want to use Stylesheets, you can use the angular ngStyle attribute
https://docs.angularjs.org/api/ng/directive/ngStyle
example:
HTML:
<div ng-app="OddEven">
<ul ng-controller="oddEvenController">
<li ng-repeat="item in list" ng-style="$index % 2 == 0 ? {'color':'blue'} : {color:'red'}">{{item}}</li>
</ul>
</div>
JS:
var angularApp = angular.module("OddEven",[]);
angularApp.controller("oddEvenController", function($scope) {
$scope.list = ["a", "b", "c", "d", "e", "f"];
});
If you can use Stylesheets, look at the accepted answer of
How to assign alternate class to rows in Angular JS?

How to show only one row in angular datatable?

I am new to angularjs, i have 25 rows to show, but for first time loading i am trying to show only one row, there will be one expand button to show remaining rows, then on click of expand i want to show all the rows.
Here is the code.
<table>
<tbody>
<tr ng-repeat="x in names">
<td>{{x}}</td>
</tr>
</tbody>
</table>
You can use:
<div ng-repeat="x in names | limitTo: limit">
<p>{{x}}</p>
</div>
$scope.limit = 1;
and on ng-click you can set your limit like: ng-click='limit = names.length'
This is what you can try.
<div ng-init="limit= 1">
<button ng-click="limit=names.length">View</button>
<table>
<tbody>
<tr ng-repeat="x in names | limitTo: limit">
<td>{{x}}</td>
</tr>
</tbody>
</table>
</div>
https://jsfiddle.net/alpeshprajapati/7MhLd/2252/
Try limitTo filter :
The limitTo filter returns an array or a string containing only a specified number of elements.
Syntax :
{{ object | limitTo : limit }}
As per the requirement :
Js :
var app = angular.module('myApp', []);
app.controller('MyCtrl',function($scope) {
$scope.elements = ["1", "2", "3", "4", "5"];
$scope.limit = 1;
});
Html :
<button ng-click="limit=elements.length">Expand More</button>
<table>
<tr ng-repeat="item in elements | limitTo: limit">
<td>{{item}}</td>
</tr>
</table>
Working fiddle : https://jsfiddle.net/rohitjindal/vcxvvecr/2/
// Angular `slice` filter for arrays
var app = angular.module('myApp', []);
app.filter('slice', function() {
return function(arr, start, end) {
return arr.slice(start, end);
};
});
app.controller('MainController', function($scope) {
$scope.offset = 1;
$scope.items = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller='MainController' ng-init="start = 0;">
<ul>
<li ng-repeat="item in items | slice:start:offset">{{item}}</li>
</ul>
<button ng-click="offset = items.length">Expand</button>
</div>
</div>
I use slice for limit set
You can also try with:
limitTo: (limit) : (begin)
you can say ng-repeat="item in list | limitTo:50:0"
Limit the rows by set a scope variable in the controller and filter it in the ng-repeat.
Script:
var app = angular.module('myApp', []);
app.controller('limitCtrl',function($scope) {
$scope.limitNumber = 1;
});
Html:
<table>
<tbody>
<tr ng-repeat="x in names | limitTo: limitNumber">
<td>{{x}}</td>
</tr>
</tbody>
</table>

Getting AngularJS orderBy to sort both directions

I'm attempting to setup a clickable table column header that sort Ascending when first clicked, and Descending when clicked again. My ascending sort is working fine, but I'm not sure how to setup an expression within my OrderBy to sort Descending
My setup thus far:
Table html has something like
<th ng-click="sort('LastName')">Last Name</th>
My sort method looks like
scope.sort = function (columnName) {
if (angular.isDefined(scope.filter)) {
if (scope.filter.SortColumn == columnName) {
scope.filter.SortColumn = columnName;
scope.filter.SortDirection = scope.filters.SortDirection == "Asc" ? "Desc" : "Asc";
} else {
scope.filter.SortColumn = columnName;
scope.filter.SortDirection = "Asc";
}
}
};
And my ng-repeat looks as follows
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn">
How can I get the SortDirection to factor into the orderBy?
To simply reverse you'd change it to this:
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn : true">
It'd be best if you used a boolean in your controller, but this should work too:
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn : filter.SortDirection === 'Desc'">
And just for fun, here's how I do sorting with filtering in my tables.
Controller:
$scope.search = { query: ''};
$scope.sort = { field: 'defaultField', descending: true};
$scope.order = function(newValue) {
if(newValue === $scope.sort.field) {
$scope.sort.descending = !$scope.sort.descending;
} else {
$scope.sort = {field: newValue, descending: false};
}
};
$scope.filteredDocuments = function() {
var a = $filter('filter')($scope.documents, {$:$scope.search.query});
var b = $filter('orderBy')(a, $scope.sort.field, $scope.sort.descending);
return b;
};
A search box for filtering:
<input type="text" ng-model="search.query">
A column header:
<th nowrap>
<a href ng-click="order('size')">Size </a>
<i ng-show="sort.field === 'size' && !sort.descending" class="fa fa-sort-amount-asc"></i>
<i ng-show="sort.field === 'size' && sort.descending" class="fa fa-sort-amount-desc"></i>
</th>
The row binding:
<tr ng-repeat="d in filteredDocuments()" >
A simplified version of the above answer:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<p>Click the table headers to change the sorting order:</p>
<div ng-app="myApp" ng-controller="namesCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')" >Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:mySortOrder">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.sorts={};
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
if(x in $scope.sorts) {
$scope.sorts[x]=!$scope.sorts[x];
} else {
$scope.sorts[x]=false;
}
$scope.mySortOrder=$scope.sorts[x];
}
});
</script>
</body>
</html>

Issue with Angular JS

I am a UI developer and I am completely new to Angular, however, I understand jQuery. I have joined a new company and they use Angular JS with JAVA. I have been assigned a task over which I am banging head for the past few days. I've come under the scanner now.
Basically I have a table in .html page to which data is coming (Sorry, I am told that I would need atleast 10 reputation to post a screen shot). Now I want to other column in that table.
I have tried adding that column in columns_panel.js but still it is not coming in the grid by default.
I understand that my question is not clear over here, but trust me, even my Team lead is also not willing to disclose any thing.
Can any JS guru's be help to me?
<div columns-panel columns="columns" show-panel="showColumnsPanel"></div>
<table class="responsive">
<thead>
<tr>
<th>
</th>
<th class="isFlagged">
<div class="flag"></div>
</th>
<th ng-repeat="column in columns" ng-click="sortBy(column)" class="{{ column }}">
<a class="th-inner">
{{ column | translate }}
<span ng-show="isSortColumn(column)"
ng-class="{'sort-icon-desc': !isSortAscending(),
'sort-icon-asc': isSortAscending()}">
</span>
</a>
</th>
<!--<th class="toggle-columns-header">-->
<!--<a class="th-inner" ng-click="showColumnsPanel = !showColumnsPanel">+</a>-->
<!--</th>-->
</tr>
</thead>
<tbody>
<tr ng-repeat="dispute in disputes.currentPage"
ng-class="isSelected(dispute) ? '{{ dispute | disputeTrClass }} checked-dispute' : '{{ dispute | disputeTrClass }}'"
ng-click="goToDisputeDetails(dispute)">
<td ng-class="isNegative(dispute) ? 'select-dispute alert-corner' : 'select-dispute'" ng-click="$event.stopPropagation()">
<input id="select-dispute-{{ dispute.id }}" type="checkbox" ng-click="toggleSelectedDispute(dispute)" ng-checked="isSelected(dispute)" ng-disabled="!dispute.isFlaggable" ng-hide="!dispute.isFlaggable" />
<label for="select-dispute-{{ dispute.id }}" ng-hide="!dispute.isFlaggable"></label>
</td>
<td class="isFlagged" ng-click="toggleFlag(dispute, $event)">
<div ng-show="dispute.isFlaggable" class="flag {{ dispute.isFlagged ? 'flagged' : 'unflagged' }}"></div>
</td>
<td ng-repeat="column in columns" class="{{ column }}">
<div data-ng-switch data-on="column">
<div data-ng-switch-when="reason">
{{ dispute[column] }}
<span class="reason-code" ng-if="dispute.reason !== 'N/A'">{{ dispute.reasonCode }}</span>
</div>
<div data-ng-switch-when="status">
{{ dispute[column]=="Urgent Response Required"?"Response Required":dispute[column] }}
</div>
<div data-ng-switch-when="amount">
<div ng-if="isNegative(dispute)" class="negative">
-<span class="currency">$</span>{{ dispute[column] * -1 | number:2 }}
</div>
<div ng-if="isPositive(dispute)">
<span class="currency">$</span>{{ dispute[column] | number:2 }}
</div>
</div>
<div data-ng-switch-when="dateReceived">
{{ dispute[column] | translatedDate }}
</div>
<div data-ng-switch-when="respondBy">
{{ dispute[column] | translatedDate }}
</div>
<div data-ng-switch-when="respondedOn">
{{ dispute[column] | translatedDate }}
</div>
<div data-ng-switch-default>
{{ dispute[column] }}
</div>
</div>
</td>
<!--<td class="{{ columns[columns.length - 1] }}"></td>-->
</tr>
</tbody>
</table>
<!-- No Disputes To Display -->
<div disputes-table-empty></div>
<!-- Error Message -->
<div disputes-table-error></div>
<style type="text/css">
.status {
padding-left: 27px !important;
}
</style>
This is the Model
DisputeModule.value('Dispute', function (attributes) {
this.id = attributes.id;
this.amount = attributes.amount;
this.cancelDate = attributes.cancelDate;
this.cancellationNumber = attributes.cancellationNumber;
this.cancelZone = attributes.cancelZone;
this.cardDeposit = attributes.cardDeposit;
this.cardMemberName = attributes.cardMemberName;
this.cardNumber = attributes.cardNumber;
this.chargeAmount = attributes.chargeAmount;
this.chargeDate = attributes.chargeDate;
this.creditReceived = attributes.creditReceived;
this.dateReceived = attributes.dateReceived;
this.disputeNumber = attributes.disputeNumber;
this.description = attributes.description;
this.isFlaggable = attributes.isFlaggable;
this.isFlagged = attributes.isFlagged;
this.locationID = attributes.locationID;
this.merchandiseReturned = attributes.merchandiseReturned;
this.merchandiseType = attributes.merchandiseType;
this.merchantAccount = attributes.merchantAccount;
this.modeOfReturn = attributes.modeOfReturn;
this.originalCardNbr = attributes.originalCardNbr;
this.payeeLocationId = attributes.payeeLocationId;
this.payeeSENbr = attributes.payeeSENbr;
this.reason = attributes.reason;
this.reasonCode = attributes.reasonCode;
this.referenceNumber = attributes.referenceNumber;
this.reservationCanceled = attributes.reservationCanceled;
this.reservationCanceledDate = attributes.reservationCanceledDate;
this.stage = attributes.stage;
this.status = attributes.status;
});
This is the columns_panel.js
DisputeModule.directive('columnsPanel', function (BASE_URL) {
var defaultColumns = [
'disputeNumber',
'status',
'dateReceived',
'respondBy',
'respondedOn',
'type',
'reason',
'cardNumber',
'originalCardNbr',
'transactionDate',
'referenceNumber',
'resolution',
'merchantAccount',
'locationID',
'payeeSENbr',
'payeeLocationId',
'chargeAmount',
'amount'
];
var availableColumns = [
'disputeNumber',
'status',
'dateReceived',
'respondBy',
'respondedOn',
'type',
'reason',
'cardNumber',
'originalCardNbr',
'transactionDate',
'referenceNumber',
'resolution',
'merchantAccount',
'locationID',
'payeeSENbr',
'payeeLocationId',
'chargeAmount',
'amount'
];
var columns = defaultColumns.slice();
return {
templateUrl: BASE_URL + '/resources/views/columns_panel.html',
scope: {
columns: '=',
showPanel: '='
},
controller: function ($scope) {
function addColumn(column) {
var tmpColumns = $scope.columns.slice();
tmpColumns.push(column);
tmpColumns.sort(function (a, b) {
return $scope.availableColumns.indexOf(a) - $scope.availableColumns.indexOf(b);
});
updateColumns(tmpColumns);
}
$scope.columns = columns;
$scope.availableColumns = availableColumns;
$scope.isSelected = function (column) {
return $scope.columns.indexOf(column) > -1;
};
$scope.toggleColumn = function (column) {
var columnIndex = $scope.columns.indexOf(column);
if (columnIndex === -1) {
addColumn(column);
} else {
$scope.columns.splice(columnIndex, 1);
}
};
$scope.reset = function () {
updateColumns(defaultColumns.slice());
};
$scope.close = function () {
$scope.showPanel = false;
};
function updateColumns(newColumns) {
$scope.columns = columns = newColumns;
}
}
};
});
I want to add "chargeAmount" to appear in the grid/table
you must have another columns somewhere, this columns
<div columns-panel columns="columns" show-panel="showColumnsPanel"></div>
try to add to your directive datas (the columns).
they are called here
scope: {
columns: '=',
showPanel: '='
},
and gave to the directive scope here
$scope.columns = columns;
so in your controller try to see what you have in columns

Resources