Angular Javascript find method - javascript

Here's my code:
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.controller('MyCtrl', ['$scope', MyCtrl]);
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.names = [
{
"name": "AAAAAA",
"down": "False"
},
{
"name": "BBBBBB",
"down": "45%"
},
{
"name": "CCCCC",
"down": "12%"
}
];
$scope.datas = [
{
"data": "AAAAAA/45%"
}
];
$scope.getTheRightData = data => $scope.datas.map(d=>d.data.split('/')[0]).find(d=>d===data);
}
HTML
<div ng-controller="MyCtrl">
<table>
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.down}}</td>
<td ng-bind="getTheRightData(name.name)"></td>
</tr>
</tbody>
</table>
What i do : one element from $scope.datas will match an element in $scope.names, but it only shows when name.name is the same. I need when name.name and name.down is the same, something like this : <td ng-bind="getTheRightData(name.name,name.down)"></td>, and in controller
$scope.getTheRightData = data => $scope.datas.map(d=>d.data.split('/')[0][1]).find(d=>d===data);
}
, but it dont work.
Thanks for answers and ideas for advance!

I created a sample answer check the below code.
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.controller('MyCtrl', ['$scope', MyCtrl]);
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.names = [{
"name": "AAAAAA",
"down": "False"
}, {
"name": "BBBBBB",
"down": "45%"
}, {
"name": "CCCCC",
"down": "12%"
}, {
"name": "AAAAAA",
"down": "45%"
}];
$scope.datas = [{
"data": "AAAAAA/45%"
}, {
"data": "CCCCC/12%"
}];
$scope.getTheRightData = data => $scope.datas.map(param => {
return {
name: param.data.split('/')[0],
down: param.data.split('/')[1]
}
}).find(param => param.name == data.name && param.down == data.down);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myApp">
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div ng-controller="MyCtrl">
<table>
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.down}}</td>
<td>{{getTheRightData(name)}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

Related

Calculation of the sum of repeating elements within a filter using the FILTER function of AngularJS

I have a list that shows the total of the records, when filtering a single name it still shows me the total of the records and not the total of the filtered record. TRY HERE
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
name:
<input type="text" ng-model="model_filter">
<hr/>
<table ng-controller="myCtrl" border="1">
<tr ng-repeat="x in records | filter: model_filter">
<td>{{x.Name}}</td>
<td>{{x.Money | currency}}</td>
</tr>
<tr>
<td>TOTAL</td>
<td>{{Total | currency}}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.records = [
{
"Name": "Rodrigo",
"Money": 10
},
{
"Name": "Rodrigo",
"Money": 25
},
{
"Name": "Arnodl",
"Money": 15
},
{
"Name": "Carlos",
"Money": 5
}
]
$scope.Total = 0;
for (var i = 0; i < $scope.records.length; i++) {
$scope.Total += $scope.records[i].Money;
}
});
</script>
</body>
</html>
RESULT:
WITH FILTER:
MY PROBLEM
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
name:
<input type="text" ng-model="model_filter">
<hr/>
<table ng-controller="myCtrl" border="1">
<tr ng-repeat="x in records | filter: model_filter">
<td>{{x.Name}}</td>
<td>{{x.Money | currency}}</td>
</tr>
<tr>
<th>TOTAL</th>
<td>{{Total()}}</td>
</tr>
<tr>
<th>TotalFiltered</th>
<td>{{ TotalFiltered() }}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [{
"Name": "Rodrigo",
"Money": 10
},
{
"Name": "Rodrigo",
"Money": 25
},
{
"Name": "Arnodl",
"Money": 15
},
{
"Name": "Carlos",
"Money": 5
}
]
$scope.Total = () => $scope.records.reduce((total, b) => total + b.Money, 0);
$scope.TotalFiltered = () => {
return $scope.records.reduce((total, b) => {
if ($scope.model_filter && b.Name.toUpperCase().includes($scope.model_filter.toUpperCase())) { return total + b.Money; }
else { return total; }
}, 0);
}
});
</script>
</body>
</html>
To achieve expected result , use below option
Use scope variabled for filtered values
ng-repeat="x in filteredValues = (records | filter: model_filter)"
2.Use ng-keyup to get filtered values on input field
<input type="text" ng-model="model_filter" ng-keyup="calcTotal($event)">
3. In Key up event, calculate total again with filtered values
$scope.calcTotal = function(e){
$scope.Total = 0;
for (var i = 0; i < $scope.filtered.length; i++) {
$scope.Total += $scope.filtered[i].Money;
}
}
codepen - https://codepen.io/nagasai/pen/KjPrvr
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
name:
<input type="text" ng-model="model_filter" ng-keyup="calcTotal($event)">
<hr/>
<table border="1">
<tr ng-repeat="x in filteredValues = (records | filter: model_filter)">
<td>{{x.Name}}</td>
<td>{{x.Money | currency}}</td>
</tr>
<tr>
<td>TOTAL</td>
<td>{{Total | currency}}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.calcTotal = function(e){
$scope.Total = 0;
for (var i = 0; i < $scope.filteredValues.length; i++) {
$scope.Total += $scope.filteredValues[i].Money;
}
}
$scope.records = [
{
"Name": "Rodrigo",
"Money": 10
},
{
"Name": "Rodrigo",
"Money": 25
},
{
"Name": "Arnodl",
"Money": 15
},
{
"Name": "Carlos",
"Money": 5
}
]
$scope.Total = 0;
for (var i = 0; i < $scope.records.length; i++) {
$scope.Total += $scope.records[i].Money;
}
});
</script>
</body>
</html>
Issue from your code:
Calculating total on $scope.records which remains same always event with filter and without filter
Total is getting calculated on intial load with $scope.records and not with filter

Different alerts on a button click

My task is to display a table using ng-repeat, say for eg: 1234567 with a button on each row. On click of the button, I want to display an alert with the corresponding number.
The following is my HTML file.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="myApp.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="x in records">
<td>{{x.Digit}}</td>
<td><input type="button" value="Press Me" ng-click="test(record)" /></td>
</tr>
</table>
</body>
</html>
<html>
<body>
JS file.
var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
// $scope.records = [1,2,3,4,5,6,7];
$scope.records = [
{
"Digit" : "1",
},
{
"Digit" : "2",
},
{
"Digit" : "3",
},
{
"Digit" : "4",
},
{
"Digit" : "5",
},
{
"Digit" : "6",
},
{
"Digit" : "7",
}
]
$scope.test = function(text) {
alert("You clicked");
// alert(text);
}
// }).directive('li',function(){
// return {
// template: '<records> <record ng-click="test(record)" ng-repeat="record in records"> {{ record }} </record></br></records> '
// }
// });
// app.controller("myCtrl", function($scope) {
// $scope.myFunction = function(text){
// alert(text);
// };
});
Since your iterator is x, So pass x.digit, not record.
<tr ng-repeat="x in records">
<td>{{x.Digit}}</td>
<td><input type="button" value="Press Me" ng-click="test(x.Digit)" /></td>
</tr>
you need to pass x not record
<tr ng-repeat="x in records">
<td>{{x.Digit}}</td>
<td><input type="button" value="Press Me" ng-click="test(x.Digit)" /></td>
</tr>
DEMO
var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
// $scope.records = [1,2,3,4,5,6,7];
$scope.records = [
{
"Digit" : "1",
},
{
"Digit" : "2",
},
{
"Digit" : "3",
},
{
"Digit" : "4",
},
{
"Digit" : "5",
},
{
"Digit" : "6",
},
{
"Digit" : "7",
}
]
$scope.test = function(text) {
alert("You clicked "+ text);
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="x in records">
<td>{{x.Digit}}</td>
<td><input type="button" value="Press Me" ng-click="test(x.Digit)" /></td>
</tr>
</table>
</body>
</html>
<html>
<body>

Nested ng-repeat with ng-if condition for skip the nested array

I have one JSON array...
{
"Name" : "ABC",
"rating": [
{
"id": null,
"Percentage": 40
},
{
"id": 0,
"Percentage": 40
},
{
"id": 1,
"Percentage": 20
}
],
"email" : "abc#abc.com"
}
And i want to get only percentage with id 0 and 1 not null(skip)...
I am displaying this array in html with ng-repeat..., and i want to display only percentages with id is equal to 0 and 1 not null (skip).
This should be the ng-repeat for the array structure:
<div
ng-repeat="item in items"
ng-show="item.id != null && item.id == 0 || item.id == 1">
</div>
This is the array only, not the json object, you'll have to loop through that too prior to this.
If you only want to have those in the HTML, which 0 or 1 in the HTML, you can use the following code snippet:
HTML:
<div ng-repeat="rating in object.rating | filter: skipNull">
Angular Controller:
$scope.skipNull = function(item) {
return item.id === 0 || item.id === 1;
}
Here is a JSFiddle.
You are probably better off, if you are using a function like this, which only checks for null and undefined:
$scope.skipNull = function(item) {
return (typeof item.id !== "undefined" && item.id !== null);
}
You can use a custom filter. Like in this answer.
angular.module('app', []).
controller('ctrl', function($scope) {
$scope.data = {
"Name" : "ABC",
"rating": [
{
"id": null,
"Percentage": 40
},
{
"id": 0,
"Percentage": 40
},
{
"id": 1,
"Percentage": 20
}
],
"email" : "abc#abc.com"
};
$scope.noNull = function(item) {
return item.id != null;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<ul>
<li ng-repeat="item in data.rating | filter:noNull" ng-bind="item.Percentage"></li>
</ul>
</div>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.results = [{
"Name": "ABC",
"rating": [{
"id": null,
"Percentage": 40
}, {
"id": 0,
"Percentage": 40
}, {
"id": 1,
"Percentage": 20
}],
"email": "abc#abc.com"
}] ;
$scope.resultstobeDisplayed = [];
angular.forEach($scope.results[0].rating, function(val) {
if (val.id != null) {
$scope.resultstobeDisplayed.push(val);
}
});
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script src="https://code.angularjs.org/1.6.1/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="vale in resultstobeDisplayed">
<h1>{{vale}}</h1>
</div>
</body>
</html>
You can use ng-if
<div ng-repeat="rating in object.rating" ng-if="rating.id != null">
You can create your filter function into the controller like this:
Controller:
$scope.hideNullRatings = function(item) {
return item.id ===0 || item.id === 1;
}
HTML:
ng-repeat='item in items | filter: hideNullRatings'
You have to use ng-if directive. All you have to do is to apply it:
ng-if="item.id!=null"
function TodoCtrl($scope) {
$scope.data={ "Name" : "ABC", "rating": [ { "id": null, "Percentage": 40 }, { "id": 0, "Percentage": 40 }, { "id": 1, "Percentage": 20 } ], "email" : "abc#abc.com" };
}
td{
border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div ng-app>
<div ng-controller="TodoCtrl">
<table>
<tr>
<th>Id</th>
<th>Percentage</th>
</tr>
<tr ng-repeat="item in data.rating" ng-if="item.id!=null">
<td>{{item.id}}</td>
<td>{{item.Percentage}}</td>
</tr>
</table>
</div>
</div>

Ng-repeat datas from 2 json Angular

I try to get data from 2 jsons and list it in table :
1st 'names.json':
[
{
"name": "AAAAAA",
"down": "False"
},
{
"name": "BBBBBB",
"down": "45%"
},
{
"name": "CCCCC",
"down": "12%"
}
]
Second 'data.json'
[
{
"data": "25-12-2014"
}
]
Javascript:
app.service('service', function($http, $q){
this.getNames = function () {
var datas = $http.get('data,json', { cache: false});
var names = $http.get('names.json', { cache: false});
return $q.all([datas, names]);
};
});
app.controller('FirstCtrl', function($scope, service) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.names.data;
$scope.datas = data.datas.data;
});
Now i must show it in table HTML :
div ng-controller="FirstCtrl"
<table>
<tbody>
<tr ng-repeat="name in names.concat(datas)">
<td>{{name.name}}</td>
<td>{{name.data}}</td>
</tr>
</tbody>
</table>
</div>
I try concat() but it dont work, is there any method to show in table datas from 2 arrays by ng-repeat?
Thanks for answers in advance!

node tree from json data using angularjs using recursive function

I want to create a node tree from a json.
index.html should load node tree recursively from person.json
and now the method is going into infinite loop.
please help me.
app.js
(function() {
var app = angular.module("app", ['directive.cusTree', 'directive.cnode']);
app.controller("Contrl", function($scope, $http) {
$scope.some = function() {
return $http.get('person.json').success(function(data) {
$scope.nodetree = data;
return data;
});
}
});
})();
person.json
{
"person": [{
"id": 1,
"name": "A1" ,
"child": [{
"id": 1.1,
"name": "A11",
"child": [{
"id": 1.11,
"name": "A111"
}, {
"id": 1.12,
"name": "A112"
}, {
"id": 1.13,
"name": "A113"
}]
}, {
"id": 1.2,
"name": "A12"
}, {
"id": 1.3,
"name": "A13",
"child": [{
"id": 1.31,
"name": "A131"
}, {
"id": 1.32,
"name": "A132"
}, {
"id": 1.33,
"name": "A133"
}]
}]
}, {
"id": 2,
"name": "B2"
}, {
"id": 3,
"name": "C3"
}, {
"id": 4,
"name": "D4"
}
]
}
item.html
<div ng-click="show(show)" ng-init="show=true" class="container" ng-repeat="node in nodedata" ng-if="nodedata.length>0">
<ul>
{{node.name}}
<br>
<div ng-if="node.child.length>0">
<custree nodedata="node.child"> </custree>
</div>
</ul>
</div>
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="app.js" type="text/javascript"></script>
<script src="cusTree.js" type="text/javascript"></script>
<script src="cnode.js" type="text/javascript"></script>
</head>
<body>
<div ng-controller="Contrl as n">
<div ng-init="nodetree=some()">
<div ng-repeat="node in nodetree">
<div class="container">
<custree nodedata="node"> </custree>
</div>
<br>
</div>
</div>
</div>
</body>
</html>
cusTree.js
angular.module('directive.cusTree',[])
.directive('custree',function(){
return{
restrict :'E',
scope: {
nodedata:'='
},
templateUrl:"item.html",
controller:function($scope){
//console.log("new="+ JSON.stringify($scope.nodedata));
}
};
});
If you are creating tree with AngularJS, you have to create 2 directives as below:
app.directive('nodeTree', function () {
return {
template: '<node ng-repeat="node in tree"></node>',
replace: true,
restrict: 'E',
scope: {
tree: '=children'
}
};
});
app.directive('node', function ($compile) {
return {
restrict: 'E',
replace: true,
templateUrl: 'partials/node.html', // HTML for a single node.
link: function (scope, element) {
/*
* Here we are checking that if current node has children then compiling/rendering children.
* */
if (scope.node && scope.node.children && scope.node.children.length > 0) {
var childNode = $compile('<ul class="tree" ng-if="!node.visibility"><node-tree children="node.children"></node-tree></ul>')(scope);
element.append(childNode);
}
},
controller: ["$scope", function ($scope) {
// This function is for just toggle the visibility of children
$scope.toggleVisibility = function (node) {
node.visibility = !node.visibility;
};
// Here We are marking check/un-check all the nodes.
$scope.checkNode = function (node) {
node.checked = !node.checked;
function checkChildren(c) {
angular.forEach(c.children, function (c) {
c.checked = node.checked;
checkChildren(c);
});
}
checkChildren(node);
};
}]
};
});
For More details you can checkout Github Link, its have working demo.

Categories

Resources