angularjs custom filter on ng-class - angularjs

Hello I want to create simple search table of data.
I want to highlight if data matched user type input. I done it by doc below since I'm starting using angular i wonder is there any better way? Some custom filter maybe ?
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html ng-app="myApp">
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<style type="text/css">
table td{
padding: 5px;
}
.true{
color: green;
background-color: blue;
}
</style>
</head>
<body>
<div ng-controller="filtrController">
<div>{{search}}<hr/></div>
<input type="text" ng-model="search"/>
<table>
<thead>
<tr>
<td>Name:</td>
<td>Param1:</td>
<td>Param2:</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="foo in data | filter:search">
<!--<td ng-class="{true:'true',false:''}[search === foo.Name]">{{foo.Name}}</td>-->
<td ng-class="customFilter(search,foo.Name)">{{foo.Name}}</td>
<td ng-class="customFilter(search,foo.param1)">{{foo.param1}}</td>
<td ng-class="customFilter(search,foo.param2)">{{foo.param2}}</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
var myApp = angular.module('myApp',[]);
myApp.controller('filtrController',function ($scope)
{
$scope.customFilter = function(search,searchTo)
{
if(search != '')
{
if(searchTo.indexOf(search) > -1) return 'true';
return '';
}
};
$scope.data =
[
{
Name:'name foo1',
param1:'param of foo1',
param2:'param 2 of foo1'
},
{
Name:'name foo2',
param1:'param of foo2',
param2:'param 2 of foo2'
},
{
Name:'name sfoo3',
param1:'param of foo3',
param2:'param 2 of foo3'
},
]
});
</script>
</body>

You just need to custom filter like this:
$scope.customFilter = function(data, searchFor) {
if (angular.isUndefined(data) || angular.isUndefined(searchFor)) return data;
angular.forEach(data, function(item) {
if(angular.equals(item, searchFor)) item.highlighted = true;
});
return data;
}
and html like this
<tr ng-repeat="foo in data | customFilter:{something:1}" ng-class="{highlighted: foo.highlighted}">
Update:
So, I just need to explain my approach in more details. You have data some of which is needed to be highlighted. So you need to set new property in your data and highlight it (using css and ng-class) if property set to true.
For setting this property you can create custom filter that takes your data array, changes it internal state by setting this property and return this array as result. This is what I implemented for you.
Update#2
Same behaviour as ng-filter needed. So here it is.

Related

Display all childs in Firebase Database (Web)

So I successfully displaying 1 database from my firebase using limitToLast function. Here is the webpage look like
Kinda curious how to display all of my databases (all childs from selected parent) from firebase console using javascript?
List of my database in firebase that I want to display
and here is my code below:
firebase.initializeApp(config);
var order = firebase.database().ref("order");
order.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (error) {
console.log("Error: " + error.code);
});
var submitOrder = function () {
var orderId = $("#orderOrderId").val();
var shipping = $("#orderShipping").val();
var subtotal = $("#orderSubtotal").val();
var total = $("#orderTotal").val();
};
order.limitToLast(1).on('child_added', function(childSnapshot) {
order = childSnapshot.val();
$("#orderId").html(order.orderId)
$("#shipping").html(order.shipping)
$("#subtotal").html(order.subtotal)
$("#total").html(order.total)
$("#link").attr("https://wishywashy-179b9.firebaseio.com/", order.link)
});
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.css" />
<!-- <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script> -->
<!-- Load the jQuery library, which we'll use to manipulate HTML elements with Javascript. -->
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<!-- Load Bootstrap stylesheet, which will is CSS that makes everything prettier and also responsive (aka will work on all devices of all sizes). -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<!-- <script type = "text/javascript" src = "data.js"></script> -->
<body>
<script type = "text/javascript" src = "data.js"></script>
<div class="container">
<h1>Merchant Portal</h1>
<h3>Order Lists</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Order ID</th>
<th>Shipping Price</th>
<th>Subtotal</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<!-- This is empty for now, but it will be filled out by an event handler in application.js with the most recent recommendation data from Firebase. -->
<td id="orderId"></td>
<td id="shipping"></td>
<td id="subtotal"></td>
<td id="total"></td>
</tr>
</tbody>
</table>
</body>
</html>
You will need to generate a new <tr> for each order. A very simple way to do this is simply generate the DOM elements in your on('child_added' callback:
var table = document.querySelector("tbody");
order.on('child_added', function(childSnapshot) {
order = childSnapshot.val();
var tr = document.createElement('tr');
tr.appendChild(createCell(order.orderId));
tr.appendChild(createCell(order.shipping));
tr.appendChild(createCell(order.subTotal));
tr.appendChild(createCell(order.total));
table.appendChild(tr);
});
As you can see, this code creates a new <tr> for each child/order, and populates that with simple DOM methods. It then adds the new <tr> to the table.
This code uses a simple helper function to handle the repetitious creating of <td> elements with a text node in them:
function createCell(text) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(text));
return td;
}

Angular Js swap columns in table

I would like to swap 2 columns in a table. Finally, I succeeded the change, but only the data. The attributes of the cell (style, id, class) didn't move. I tried to move attributes with jquery (i know, not an elegant method), but it was only symptomatic treatment. After clicking the data reload button, the attributes restored.
How can I change the columns order with all attributes?
my code: https://codepen.io/qwertz_/pen/YxWMBO
<!DOCTYPE html>
<html>
<head>
<title>angT</title>
<script type="text/javascript" src="http://code.angularjs.org/angular-1.0.0rc10.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
th, td{padding: 3px 20px;border: 1px solid red;}
</style>
</head>
<body>
<div ng-controller="MyCtrl" ng-app="myApp">
<button ng-click="swap(0)">first2second</button>
<button ng-click="reload()">reload</button>
<table id="myTable" >
<tr ng-repeat="row in ths">
<th class="oo1">{{col(row, 0)}}</th>
<th class="oo2">{{col(row, 1)}}</th>
<th class="oo3">{{col(row, 2)}}</th>
<th class="oo4">{{col(row, 3)}}</th>
</tr>
<tr ng-repeat="row in rows">
<td class="o1" style="background-color:yellow;">{{col(row, 0)}}</td>
<td class="o2" style="background-color:pink;">{{col(row, 1)}}</td>
<td class="o3" style="background-color:green;">{{col(row, 2)}}</td>
<td class="o4" style="background-color:blue;">{{col(row, 3)}}</td>
</tr>
</table>
</div>
<script type='text/javascript'>
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.mycol = new Array();
$scope.mycol[0] = 'id';
$scope.mycol[1] = 'name';
$scope.mycol[2] = 'db';
$scope.mycol[3] = 'let';
$scope.reload = function()
{
$scope.rows=[{id:parseInt(Math.random()*10000),name:"Liv","db":21,let:"r"},{id:parseInt(Math.random()*10000),name:"Mike",db:30,let:"u"}];
};
$scope.swap = function(i) {
var temp = $scope.mycol[i];
$scope.mycol[i] = $scope.mycol[(i+1)];
$scope.mycol[(i+1)] = temp;
};
$scope.col = function(row, mycol) {
return row[$scope.mycol[mycol]];
};
$scope.reload();
$scope.ths=[{id:"id",name:"name","db":"db",let:"letter"}];
}
</script>
</body>
Thx a lot
Simple way
You can bind colors to header name as:
$scope.styles = {
id: "yellow",
name: "pink"
};
and table will look like:
<tr ng-repeat="row in rows">
<td class="o1" ng-style="{'background-color':styles[mycol[0]]}">{{col(row, 0)}}</td>
<td class="o2" ng-style="{'background-color':styles[mycol[1]]}">{{col(row, 1)}}</td>
<td class="o3" style="background-color:green;">{{col(row, 2)}}</td>
<td class="o4" style="background-color:blue;">{{col(row, 3)}}</td>
</tr>
Once header value changes, colors will change too
Codepen DEMO
More complicated but generic
You can achieve it by replacing all table with directive (headers + data) and by using $compile rebuild all HTML table.

Filtering ng-repeat result set is not working

I tried to create a textbox based filtering of a ng-repeat result. Though there is no errors listed, the filtering is not working. What is missing here?
Updated code after making following change:
<tbody ng-repeat="objReview in reviewsList | myCustomFilter:criteria" >
The filter is gettiing called two times for each row. How to make it call only once?
Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-resource.js"></script>
<style type="text/CSS">
table
{border-collapse: collapse;width: 100%;}
th, td
{text-align: left;padding: 8px;}
tr:nth-child(even)
{background-color: #f2f2f2;}
th
{background-color: #4CAF50;color: white;}
</style>
<script type="text/javascript">
//defining module
var app = angular.module('myApp', ['ngResource']);
//defining factory
app.factory('reviewsFactory', function ($resource) {
return $resource('https://api.mlab.com/api/1/databases/humanresource/collections/Reviews',
{ apiKey: 'myKey' }
);
});
//defining controller
app.controller('myController', function ($scope, reviewsFactory)
{
$scope.criteria = "";
$scope.reviewsList = reviewsFactory.query();
});
app.filter('myCustomFilter', function ()
{
return function (input, criteria)
{
var output = [];
if (!criteria || criteria==="")
{
output = input;
}
else
{
angular.forEach(input, function (item)
{
alert(item.name);
//alert(item.name.indexOf(criteria));
//If name starts with the criteria
if (item.name.indexOf(criteria) == 0)
{
output.push(item)
}
});
}
return output;
}
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<label>
SEARCH FOR: <input type="text" ng-model="criteria">
</label>
<table>
<thead>
<tr>
<th>Name</th>
<th>Review Date</th>
</tr>
</thead>
<tbody ng-repeat="objReview in reviewsList | myCustomFilter:criteria" >
<tr>
<td>{{objReview.name}}</td>
<td>{{objReview.createdOnDate}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Further Reading
Is this normal for AngularJs filtering
How does data binding work in AngularJS?
As noted in the comments by Lex you just need to get rid of the prefix 'filter', so change
<tbody ng-repeat="objReview in reviewsList | filter:myCustomFilter:criteria" >
to
<tbody ng-repeat="objReview in reviewsList | myCustomFilter:criteria" >
In addition you should set an initial value for your controller's property criteria as otherwise your initial list will be empty as your filter will not match anything due to the comparison operator === which takes the operands' types into account and critiera will be undefined until you first enter something in your textbox.
app.controller('myController', function ($scope, reviewsFactory)
{
$scope.criteria = '';
$scope.reviewsList = reviewsFactory.data();
});

AngularJS ng-click not firing controller method

I'm sure everyone has seen questions of a similar ilk, and trust me when I say I have read all of them in trying to find an answer. But alas without success. So here goes.
With the below code, why can I not get an alert?
I have an ASP.Net MVC4 Web API application with AngularJS thrown in. I have pared down the code as much as I can.
I know that my AngularJS setup is working correctly because on loading my view it correctly gets (via a Web API call) and displays data from the database into a table (the GetAllRisks function). Given that the Edit button is within the controller, I shouldn't have any scope issues.
NB: the dir-paginate directive and controls are taken from Michael Bromley's excellent post here.
I would appreciate any thoughts as my day has degenerated into banging my head against my desk.
Thanks,
Ash
module.js
var app = angular.module("OpenBoxExtraModule", ["angularUtils.directives.dirPagination"]);
service.js
app.service('OpenBoxExtraService', function ($http) {
//Get All Risks
this.getAllRisks = function () {
return $http.get("/api/RiskApi");
}});
controller.js
app.controller("RiskController", function ($scope, OpenBoxExtraService) {
//On load
GetAllRisks();
function GetAllRisks() {
var promiseGet = OpenBoxExtraService.getAllRisks();
promiseGet.then(function (pl) { $scope.Risks = pl.data },
function (errorPl) {
$log.error("Some error in getting risks.", errorPl);
});
}
$scope.ash = function () {
alert("Bananarama!");}
});
Index.cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="OpenBoxExtraModule">
<head>
<title>Risks</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="~/Scripts/angular.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/Pagination/dirPagination.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/module.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/service.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/controller.js"></script>
</head>
<body>
<div ng-controller="RiskController">
<table>
<thead>
<tr>
<th>Risk ID</th>
<th>i3_n_omr</th>
<th>i3_n_2_uwdata_key</th>
<th>Risk Reference</th>
<th>Pure Facultative</th>
<th>Timestamp</th>
<th></th>
</tr>
</thead>
<tbody>
<tr dir-paginate="risk in Risks | itemsPerPage: 15">
<td><span>{{risk.RiskID}}</span></td>
<td><span>{{risk.i3_n_omr}}</span></td>
<td><span>{{risk.i3_n_2_uwdata_key}}</span></td>
<td><span>{{risk.RiskReference}}</span></td>
<td><span>{{risk.PureFacultative}}</span></td>
<td><span>{{risk.TimestampColumn}}</span></td>
<td><input type="button" id="Edit" value="Edit" ng-click="ash()"/></td>
</tr>
</tbody>
</table>
<div>
<div>
<dir-pagination-controls boundary-links="true" template-url="~/Scripts/AngularJS/Pagination/dirPagination.tpl.html"></dir-pagination-controls>
</div>
</div>
</div>
</body>
</html>
you cannot use ng-click attribute on input with angularjs : https://docs.angularjs.org/api/ng/directive/input.
use onFocus javascript event
<input type="text" onfocus="myFunction()">
or try to surround your input with div or span and add ng-click on it.
I've got the working demo of your app, code (one-pager) is enclosed below, but here is the outline:
removed everything concerning dirPagination directive, replaced by ngRepeat
removed $log and replaced by console.log
since I don't have a Web API endpoint, I just populated $scope.Risks with some items on a rejected promise
Try adjusting your solution to first two items (of course, you won't populate it with demo data on rejected promise)
<!doctype html>
<html lang="en" ng-app="OpenBoxExtraModule">
<head>
<meta charset="utf-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module("OpenBoxExtraModule", []);
app.service('OpenBoxExtraService', function ($http) {
//Get All Risks
this.getAllRisks = function () {
return $http.get("/api/RiskApi");
}
});
app.controller("RiskController", function ($scope, OpenBoxExtraService) {
//On load
GetAllRisks();
function GetAllRisks() {
var promiseGet = OpenBoxExtraService.getAllRisks();
promiseGet.then(function (pl) { $scope.Risks = pl.data },
function (errorPl) {
console.log("Some error in getting risks.", errorPl);
$scope.Risks = [{RiskID: "1", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"}, {RiskID: "2", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"}, {RiskID: "3", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"} ];
});
}
$scope.ash = function () {
alert("Bananarama!");}
});
</script>
</head>
<body>
<div ng-controller="RiskController">
<table>
<thead>
<tr>
<th>Risk ID</th>
<th>i3_n_omr</th>
<th>i3_n_2_uwdata_key</th>
<th>Risk Reference</th>
<th>Pure Facultative</th>
<th>Timestamp</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="risk in Risks">
<td><span>{{risk.RiskID}}</span></td>
<td><span>{{risk.i3_n_omr}}</span></td>
<td><span>{{risk.i3_n_2_uwdata_key}}</span></td>
<td><span>{{risk.RiskReference}}</span></td>
<td><span>{{risk.PureFacultative}}</span></td>
<td><span>{{risk.TimestampColumn}}</span></td>
<td><input type="button" id="Edit" value="Edit" ng-click="ash()"/></td>
</tr>
</tbody>
</table>
<div>
<div></div>
</div>
</div>
</body>
</html>
Thank you all for your help, particularly #FrailWords and #Dalibar. Unbelievably, this was an issue of caching old versions of the javascript files. Doh!
You can't directly use then on your service without resolving a promise inside it.
fiddle with fallback data
this.getAllRisks = function () {
var d = $q.defer();
$http.get('/api/RiskApi').then(function (data) {
d.resolve(data);
}, function (err) {
d.reject('no_data');
});
return d.promise;
}
This will also fix your problem with getting alert to work.

Using AngularJs "ng-style" within "ng-repeat" iteration

I am tring to conditionally set the colors of data elements in a table based on their value using ng-style. Each row of data is being generated using ng repeat.
So i have something like:
<tr ng-repeat="payment in payments">
<td ng-style="set_color({{payment}})">{{payment.number}}</td>
and a function in my controller that does something like:
$scope.set_color = function (payment) {
if (payment.number > 50) {
return '{color: red}'
}
}
I have tried a couple different things. and even set the color as a data attribute in the payment object, however it seems I cant get ng-style to process data from the data bindings,
Does anyone know a way I could make this work? Thanks.
Don't use {{}}s inside an Angular expression:
<td ng-style="set_color(payment)">{{payment.number}}</td>
Return an object, not a string, from your function:
$scope.set_color = function (payment) {
if (payment.number > 50) {
return { color: "red" }
}
}
Fiddle
use this code
<td style="color:{{payment.number>50?'red':'blue'}}">{{payment.number}}</td>
or
<td ng-style="{'color':(payment.number>50?'red':'blue')}">{{payment.number}}</td>
blue color for example
It might help you!
<!DOCTYPE html>
<html>
<head>
<style>
.yelloColor {
background-color: gray;
}
.meterColor {
background-color: green;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script>
var app = angular.module('ngStyleApp', []);
app.controller('ngStyleCtrl', function($scope) {
$scope.bar = "48%";
});
</script>
</head>
<body ng-app="ngStyleApp" ng-controller="ngStyleCtrl">
<div class="yelloColor">
<div class="meterColor" ng-style="{'width':bar}">
<h4> {{bar}} DATA USED OF 100%</h4>
</div>
</div>
</body>
</html>

Resources