binding 3 arrays data using angular js - angularjs

I'm binding the array data using reference $index but i'm getting arrays in group2 and value
I need like this:
grp1
abc,def
value1,value2
grp2
adf,cdf
value3,value4
But Im getting :
grp1
["abc","def"]
[["value1","value2"]]
grp2
["adf","cdf"]
[["value3","value4"]]
Below code i tried
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
<div ng-app ng-controller="ListCtrl" ng-cloak>
<ul ng-repeat="group in group1">
<li>{{group}}</li>
<li>{{group2[$index]}}</li>
<li>{{value[$index]}}</li>
</ul>
</div>
</body>
</html>
Script:
function ListCtrl($scope) {
$scope.group1 = ['grp1', 'grp2'];
$scope.group2 = [['abc', 'def'],['adf','cdf']];
$scope.value = [[['value1','value2']],[['value3','value4']]];
}

Try hardcoded way:
<div ng-controller = "fessCntrl">
<ul ng-repeat="group in group1">
<li>{{group}}</li>
<li>{{group2[$index][0]}} {{group2[$index][1]}}</li>
<li>{{value[$index][0][0]}} {{value[$index][0][1]}}</li>
</ul>
</div>
Demo Fiddle
But if you want to invoke controller, I would write:
<div ng-controller = "fessCntrl">
<ul ng-repeat="group in group1">
<li>{{group}}</li>
<li>{{printGroup(group2[$index])}}</li>
<li>{{printGroup(value[$index])}}</li>
</ul>
</div>
and method:
$scope.printGroup = function (group) {
var buff = '';
angular.forEach(group, function(val){
buff = buff + ' ' + val
});
return buff;
};
Demo 2 Fiddle

Related

Bind particular value from array object in angularJS

testing:{"name":"Mohan,Rahul,Kanal,Rajesh,Gokul,Ramesh"}
Suppose i want first three name bind into label using angular ng-repeat.is it possible.Help me.Thanks in advance
Please review below code it may helpful to resolve your issue.
<!DOCTYPE html>
<html>
<body>
<div ng-app="myApp" ng-controller="sizeCtrl">
<ul>
<li ng-repeat="x in arr | limitTo:3">{{x}}</li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('sizeCtrl', function($scope) {
$scope.arr = [];
$scope.cars = {name: "Audi,BMW,Dodge,Fiat,Ford,Volvo"};
$scope.arr = $scope.cars.name.split(",");
});
</script>
</body>
</html>
Try like this.
var app = angular.module("app",[]);
app.controller('MainCtrl', function($scope) {
$scope.testing={"name":"Mohan,Rahul,Kanal,Rajesh,Gokul,Ramesh"}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
<div ng-repeat="(key,value) in testing.name.split(',') | limitTo:3 ">
<p >{{value}}</p>
</div>
</div>
You can use ng-repeat:
<label>
<span ng-repeat="name in testing.name.split(',') | limitTo:3">
{{name}}<span ng-show="$index<2">,</span>
</span>
</label>
Another solution: This shows first three names in array format:
{{testing.name.split(',') | limitTo:3}}
Another solution: You can split the string and then join first three into another scope variable and bind to it.
var arr = $scope.testing.name.split(',');
$scope.labelStr = "";
for(var i=0; i<3; i++) {
$scope.labelStr += arr[i] + ',';
}
$scope.labelStr = $scope.labelStr.substr(0, $scope.labelStr.length-1);

sum of values in a list using angular way

I have a short piece of sample here where myself trying to get total of values in angular way as,
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total = 0">
<ul>
<li ng-repeat="x in myarr" > {{x.val}}
<span ng-if="$last">, Total - {{total = total+x.val}}</span>
</li>
</ul>
</div>
But total is incorrect. How can it be achieved?
EDIT: Myself trying to get total within the ng-repeat loop beside last element. There is an accepted answer in this question and below answer also work in same logic. But In that method, the function getTotal() will call myarr.length times and each time the array loops in controller right? So as per example in the question, array will loop completely 6 times (myarr.length + once in ng-repeat ie, 5+1). Do i wrong?
Try this method, no function used in controller , using ng-init in ng-repeat
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total=0">
<ul >
<li ng-repeat="x in myarr" ng-init="$parent.total = $parent.total + (x.val)"> {{x.val}}
<span ng-if="$last">{{total}}</span>
</li>
</ul>
</div>
Another method ,
Use array.reduce to add sum of array Link
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
$scope.addTotal = function(){
var sum = $scope.myarr.reduce($scope.add);
return sum.val;
}
$scope.add = function(a,b){
return {val:a.val + b.val};
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total=0">
<ul >
<li ng-repeat="x in myarr" > {{x.val}}
<span ng-if="$last">{{addTotal()}}</span>
</li>
</ul>
</div>
Try doing all calculations in angular controller itself and storing it in varaible. But if you are worried about values in array constantly changing you can also use a calcTotal function in your controller. Also ng-repeat should be on li and not ul.
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total = 0">
<ul >
<li ng-repeat="x in myarr"> {{x.val}}
<span ng-if="$last">, Total - {{getTotal()}} or {{totalValue}}</span>
</li>
</ul>
</div>
Your controller will be like
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
//first approach
$scope.totalValue = 0;
for(i=0;i<$scope.myarr.length;i++){
if($scope.myarr[i] && $scope.myarr[i].val)
$scope.totalValue+=$scope.myarr[i].val;
}
//OR
//second approach
$scope.getTotal = function(){
var total = 0;
for(i=0;i<$scope.myarr.length;i++){
if($scope.myarr[i] && $scope.myarr[i].val)
total+=$scope.myarr[i].val;
}
return total;
}
});
If you are using variable approach, you will have to explicitly calculate $scope.getTotal everytime the array values change. By the function approach it will happen itself, but binding functions on UI is little expensive as they keep re-calculating on every digest cycle.
You can use angular.forEach to loop and have you total count.
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.total = 0;
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
angular.forEach($scope.myarr, function(value){$scope.total+=value.val});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="app" ng-app="myApp" ng-controller="myCtrl">
<ul >
<li ng-repeat="x in myarr" > {{x.val}}
<span ng-if="$last">{{total}}</span>
</li>
</ul>
</div>

Array Not Propagating to View

I'm very new to Angularjs and Firebase and have been stuck on this for quite some time. I'm trying to use ng-repeat to iterate over an array of procedures I set in my controller. I can print $scope.procedures in my controller but not in index.html. Any idea where I'm going wrong?
index.html
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<!-- Angular JS -->
<script src="lib/angular/angular.min.js"></script>
<!-- Firebase -->
<script src="https://cdn.firebase.com/js/client/2.2.4/firebase.js"></script>
<script src="js/controllers.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container-fluid" id="logo">
</div>
<div class="container" ng-controller="MainCtrl">
<div class="col-sm-7 col-md-6 col-md-offset-1" id="message">
<label id="input-label">Insurance Company</label>
<input ng-model="insurQuery" class="form-control insurInput" id="input-box" placeholder="Patient Insurance Company" autofocus>
<div ng-if="showProcedures()">
<h3>Procedures Covered by <span id="proc-span">{{selectedInsur.name}}</span></h3>
<ul class="list-group">
<li class="list-group-item" ng-repeat="proc in procedures">
<a>{{ proc.name }}</a>
</li>
</ul>
</div>
</div>
<div class="col-sm-4 col-md-4 col-md-offset-1" id="message2">
<ul class="list-group">
<li class="list-group-item ng-class: {'active':isSelectedInsur(company)}" ng-repeat="company in insuranceCompanies | filter: insurQuery | orderBy: 'name'">
{{ company.name }}
</li>
</ul>
</div>
</div>
</body>
</html>
controllers.js
var myApp = angular.module('myApp', ['ui.bootstrap', 'firebase']);
myApp.controller("MainCtrl", function($scope, $firebaseArray) {
var ref = new Firebase("https://payoralerts.firebaseio.com/companies");
// download the data into a local object
$scope.insuranceCompanies = $firebaseArray(ref);
$scope.selectedInsur = null;
$scope.isSelected = false;
$scope.procedures = [];
function getProcedures() {
var companiesBaseUrl = "https://payoralerts.firebaseio.com/companies/"
var proceduresBaseRef = new Firebase("https://payoralerts.firebaseio.com/procedures/");
var companyUrl = companiesBaseUrl + $scope.selectedInsur.$id + "/procedures/";
var proceduresUrl = "https://payoralerts.firebaseio.com/procedures/"
var companyProceduresRef = new Firebase(companyUrl);
companyProceduresRef.on("child_added", function(snap) {
proceduresBaseRef.child(snap.key()).once("value", function(data) {
if (data.val()) {
console.log("Name: ", data.val().name);
$scope.procedures.push(data.val());
console.log("scope procedures: ", $scope.procedures);
};
});
});
}
function setSelectedInsur(company) {
if ($scope.selectedInsur == company) {
$scope.selectedInsur = null;
$scope.isSelected = null;
} else {
$scope.selectedInsur = company;
$scope.isSelected = true;
getProcedures();
console.log("scope procedures: ", $scope.procedures);
}
}
function isSelectedInsur(company) {
return $scope.selectedInsur !== null && company.name == $scope.selectedInsur.name;
}
function showProcedures() {
if ($scope.isSelected == true) {
return true;
} else {
return false;
}
}
$scope.setSelectedInsur = setSelectedInsur;
$scope.isSelectedInsur = isSelectedInsur;
$scope.showProcedures = showProcedures;
// $scope.procedures = $scope.procedures;
});
I'm also pretty new to Angular as well and one of the most deep and hard topics in angular (imo) is how angular binding works under the hood.
In your case calling $scope.$apply() works but keep in mind that this is not the best solution and you should not start calling it whenever you have a binding problem.
I really encourage you to take some time reading some articles about what angular binding really is. You can start here and here. After this get back to your code to understand what you are doing wrong. :)

Angular Filter ng-repeat

It seems so easy but I can't get this to work:
I want ng-repeat to show the entry only when istLand == 1.
<body ng-app>
<div ng-controller="Ctrl">
<div ng-repeat="ort in orte | filter:{istLand : 1}">
{{ ort.ortsname }}
</div>
</div>
</body>
function Ctrl($scope) {
$scope.orte = {"2812197":{"ortsname":"Berlin","istLand":1},
"2829695":{"ortsname":"Munich","istLand":0}}
}
you can try something like this
<div ng-repeat="ort in orte">
<span ng-if="ort.istLand == 1">{{ ort.ortsname }} </span>
</div>
OR
your code will work if you following below structure
$scope.orte = [
{id:"2812197", ortsname:"Berlin", istLand:1},
{id:"2829695", ortsname:"Munich", istLand:0}
]
here is the Demo Fiddle
By using custom filter in angularjs, implement the same.
function Ctrl($scope) {
$scope.orte = {"2812197":{"ortsname":"Berlin","istLand":1},"2829695":{"ortsname":"Munich","istLand":0},"2829694":{"ortsname":"Delhi","istLand":1},"2829696":{"ortsname":"Beijing","istLand":0},"2829698":{"ortsname":"Sydney","istLand":1}}
}
angular.module('myApp', []).
filter('istLandCheck', function() {
return function(orte,istLand) {
var out=[];
angular.forEach(orte, function(ort,value){
if(ort.istLand==1){
out.push(ort);
}
});
return out;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="Ctrl">
<div ng-repeat="ort in orte|istLandCheck">
{{ ort.ortsname }}
</div>
</div>
</body>

How to sort array of integers in angularjs using custom filters??

here is my code , i dont know what mistake i am doing??? Is there a built in filter or function to sort array of integers or numbers??
<body data-ng-app="app" data-ng-controller="controller1" >
<div class="container">
<div class="row">
<input type="text" ng-model="searchbox" />
<li ng-repeat="num in numbers|filter:searchbox|orderBy:number">
{{num}}
</li>
</div>
</div>
<script type="text/javascript">
var app=angular.module('app', []).controller('controller1', ['$scope', function($scope){
$scope.numbers=[10,8,6,7];
$scope.number=function(data)
{
return data.sort();
}
}
]);
</script>
</body>
Check out this answer orderBy array item value in Angular ng-repeat
This means that you can do something like this:
app.controller('ctrl', ['$scope', function($scope){
$scope.numbers = [10,8,6,7];
$scope.identity = angular.identity;
}]);
And
<li ng-repeat="num in numbers | orderBy:identity">
{{num}}
</li>

Resources