Bind particular value from array object in angularJS - 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);

Related

AngularJS: How to escape JSON key that has operator in it?

This is an AngularJS syntax question.
{ "key-part": "value-part" } is a valid JSON object. However, in AngularJS, {{ x.key-part }} is an expression. It does not return "value-part" but returns 0. Any idea how to escape the '-'?
Yes, you may ask why use "key-part" instead of "key_part". Well, I have no control over that.
Thanks for any help.
You can access attributes of an object like a standard Javascript object : https://www.w3schools.com/js/js_properties.asp
So <span>{{myObject['attr']}}</span> work
"use strict";
angular.module("demo", [])
.controller("MainController", MainController);
function MainController() {
var vm = this;
vm['da-ta'] = "data";
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo" ng-controller="MainController as main">
<div ng-bind="main['da-ta']"></div>
</div>
Try {{ x["key-part"] }} instead of {{ x.key-part }}.
Working Demo
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.x = { "key-part": "value-part" };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
{{ x["key-part"] }}
</div>

How to show the ID of array objects?

I was wondering how to print ids of items inside an array.
I have and array called localData, with a list of objects inside. Every object is a mini array of 3 strings.
In my ng-repeat when i set {{items in array}} it prints the content and not the id. How can i print only ids?
localData = {"-KRFLxEmRoS7M9gKDXVE":{"postBody":"1) remove lag 2) add animations",
"postTitle":"Top Title $$$","userName":"[Admin]"},
"-KRFM6Jm2wQemtl878Ur":"postBody":"Annanana","postTitle":"Ananaj",
"userName":"[Admin]"},"-KRFM7rcEe5K5PXkb29v":{"postBody":"Abshhsua","postTitle":"Ababjsjs","userName":"[Admin]"},
"-KRFM96LtmaXRTnUXJoV":{"postBody":"Gabshsysus","postTitle":"Bshshshshs","userName":"[Admin]"},
"-KRFMAnqecr85xUcOCuw":{"postBody":"Sbsbshshsusudu","postTitle":"Ushhshshs","userName":"[Admin]"},
"-KRFMCkO3JdhA_0MlwwM":{"postBody":"Hshshshs","postTitle":"Sjjsjsjs","userName":"[Admin]"},
"-KRFMLtDJsO0fGYA9JEO":{"postBody":"Fake",
"postTitle":"OMG EPICCCCCCOOOO","userName":"[Admin]"},
"-KRFMQBwIbK6s5lVMlbW":{"postBody":"Asdrobololo","postTitle":"Asdrubale","userName":"[Admin]"},
"-KRI7TVGM0U5emvwD0i7":{"postBody":"Htrsdvgh","postTitle":"Uutfcbuj","userName":"[Admin]"},"-KRITPhL8m-qCCO9y4vY":
{"postBody":"Iiiiiiiwwwwww","postTitle":"Jjjdhd","userName":"[Admin]"}}
angular.module('myapp', [])
.controller('PostsCtrl', function($scope) {
var object={"nm_questionario":{"isEmpty":"MSGE1 - Nome do Questionário"},"ds_questionario":{"isEmpty":"MSGE1 - Descrição do Questionário"},"dt_inicio_vigencia":{"isEmpty":"MSGE1 - Data de Vigência"}};
$scope.items = [];
angular.forEach(object, function (value, key) {
$scope.items.push(key);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="PostsCtrl">
<div ng-repeat="item in items">
{{item}}
</div>
</div>
Store the local data like below to get the id easily. Try this below.
angular.module('myapp', [])
.controller('PostsCtrl', function($scope) {
var accountservice=[{"id":"1","title":"Savings Account","services":[{"types":"ATM card request"},{"types":"loan request"}]},
{"id":"2","title":"Current Account","services":[{"types":"cheque book request"},{"types":"ATM card request"}]},
{"id":"3","title":"Demat Account","services":[{"types":"loan request"},{"types":"ATM card request"}]}];
$scope.accountservices = accountservice;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="PostsCtrl">
<div ng-repeat="(key,value) in accountservices">
<p>{{value.id}}</p>
<ul><li ng-repeat="account in value.services">{{account.types}}</li></ul>
</div>
</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. :)

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>

binding 3 arrays data using angular js

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

Resources