Process a value before displaying it with AngularJS - javascript

I have a controller that update a value according to a radiobuttons list.
MyTypes = {
"cat": 0,
"dog": 1,
"cow": 2
};
function MyController($scope) {
$scope.value= 1; //Updated by a radiobuttons list
}
<!-- Display -->
<label >Type ({{value}})</label>
This would display "1". I would like to display "dog". Is there a way to call a function inside the html template? This function would find the key associated to value.

I've been doing it like this:
[snip MyTypes setup]
function MyController($scope) {
var typesById = [];
angular.forEach(MyTypes,function(v,k){typesById[+k]=v;});
$scope.typesById=typesById;
$scope.value= 1; //Updated by a radiobuttons list
}
<!-- Display -->
<label >Type ({{typesById[value]}})</label>

Related

Call field from another table in select firebase

I have a table categories and a documents. I want to create a new document and associate this document with a category already created.
The category table has the title field.
In the document creation form I want to put the categories already created in a select.
I tried doing this in the code below, but I ended up getting the select a key from the category -L0_xe_FIK9QdfTGhBDG for example, but I wanted the category title.
var documentosRef = firebase.database().ref('documentos');
var categoriasRef = firebase.database().ref('categorias');
var keyDocumento = ""
function initFirebase(){
categoriasRef.on('value', function(data) {
$('#categoria').html('');
for(categoria in data.val()){
option = "<option>"+categoria+"</option>"
$('#categoria').html($('#categoria').html()+option);
}
})
}
Structure:
{ "categorias": {
"L0_xe_FIK9QdfTGhBDG": {
"titulo": "Categorias 1"
},
"-L0a0FPFkXkKb3VNFN0c":{
"titulo": "Categorias 2"
}
}
Let check it out: JavaScript for/in Statement
var categorias = data.val();
for(var key in categorias){
option = "<option>"+categorias[key].titulo +"</option>"
$('#categoria').html($('#categoria').html()+option);
}

$$hashKey match and selected value for select menu

I am trying to set selected option for the select menu but its not working because data that I am sending to ng-model has different $$hashKey from data in the select menu and $$hashKey holding for values.
<select class="form-control" ng-model="selManga" ng-options="manga.seri for manga in mangalar">
<option value="">Manga Seçin</option>
</select>
<select ng-change="selPage = 0" ng-model="selChapter" ng-options="selManga.randomword.indexOf(chapter) as chapter.klasor for chapter in selManga.randomword">
<option value="">Bölüm</option>
</select>
<select ng-model="selPage" ng-options="selManga.randomword[selChapter].yol.indexOf(page) as selManga.randomword[selChapter].yol.indexOf(page) + 1 for page in selManga.randomword[selChapter].yol">
</select>
I google it to get around with this people says track by but I have to use as. So is there a another way to get around it?
Selected value for first select menu is working but second one is not working. Here is plunker.http://plnkr.co/edit/3V8JSF2AU01ZZNPfLECd?p=info
.controller('nbgCtrl',function ($scope, MMG, $stateParams) {
var milo = $stateParams.serix;
var musti = $stateParams.klasor;
MMG.adlar.success(function(loHemen) {
var i, miloMangaInArray;
for (i=0; i<loHemen.length; i++) {
if (loHemen[i].seri===milo) {
miloMangaInArray = loHemen[i];
break;
}
};
var a;
for (a=0; a<miloMangaInArray.randomword.length; a++) {
if(miloMangaInArray.randomword[a].klasor===musti) {
break;
}
}
$scope.mangalar = loHemen; //JSON Data
$scope.selManga = $scope.mangalar[i]; // First select menu's ng-model and its working.
$scope.selChapter = $scope.mangalar[i].randomword[a]; //Second select menu's ng-model and its not working due to no matching JSON data.
});
$scope.next = function (manga, chapter, page) {
var nextPage = page + 1;
if (angular.isDefined(manga.randomword[chapter].yol[nextPage])) {
$scope.selPage = nextPage;
} else if (angular.isDefined(manga.randomword[chapter + 1])) {
$scope.selChapter = chapter + 1;
$scope.selPage = 0;
}};
})
Dude here you go, a js fiddle for the solution
http://jsfiddle.net/yw248mfu/2/
the method I used here is indexOf to get the index of the page in the array for the last select only ,,
and this is not the best solution as it will have to apply index of every time the digest loop run ,,
I can think of a number of different solutions to this ,,
1- you can extract the id of the page from the name of the image itself
2- you can map the pages array to be a list of objects with the following schema
[{"index":1,"img":"00.jpg"},{"index":2,"img":"01.jpg"},{"index":3,"img":"02.jpg"}]
you can do the second option with this piece of code
pages.map(function(d,i){return {"index":i,"img":d};});
crouch74
I think you should embrace the AngularJS way of handling models and bindings. So, instead of keeping track of all the different indexes through your view code, you can simply let ng-select assign references to parts of your model (via ng-model). By changing the HTML and controller slightly, you can simplify some of the code, and it will actually work, too.
First, make a shared $scope.model = {…} object available on the $scope. Then, change the HTML to
<select ng-model="model.selManga" ng-options="manga.seri for manga in mangalar">
<option value="">Manga Seçin</option>
</select>
<select ng-model="model.selChapter" ng-options="chapter.klasor for chapter in model.selManga.randomword" ng-change="model.selPage = model.selChapter.yol[0]">
<option value="">Bölüm</option>
</select>
<select ng-model="model.selPage" ng-options="page as model.selChapter.yol.indexOf(page) + 1 for page in model.selChapter.yol">
</select>
<img class="picture" ng-src="http://baskimerkeziankara.com/{{model.selPage}}" ng-click="next(model.selPage)">
After that, change the controller is changed accordingly:
.controller('nbgCtrl', function($scope, MMG, $stateParams) {
var model = {
selManga: undefined,
selChapter: undefined,
selPage: undefined
};
$scope.model = model;
MMG.adlar.success(function _init(loHemen) {
for (var i = 0; i < loHemen.length; i++) {
if (loHemen[i].seri === $stateParams.serix) {
model.selManga = loHemen[i];
break;
}
}
for (var a = 0; a < model.selManga.randomword.length; a++) {
if (model.selManga.randomword[a].klasor === $stateParams.klasor) {
model.selChapter = model.selManga.randomword[a];
break;
}
}
model.selPage = model.selChapter.yol[0];
$scope.mangalar = loHemen;
});
$scope.next = function _next(page) {
var pageIndex = model.selChapter.yol.indexOf(page);
if (angular.isDefined(model.selChapter.yol[pageIndex + 1])) {
model.selPage = model.selChapter.yol[pageIndex + 1];
} else {
var chapterIndex = model.selManga.randomword.indexOf(model.selChapter);
if (angular.isDefined(model.selManga.randomword[chapterIndex])) {
pageIndex = 0;
model.selChapter = model.selManga.randomword[chapterIndex + 1];
model.selPage = model.selChapter.yol[pageIndex];
}
}
console.log('manga', model.selManga.seri,
'chapter', model.selChapter.klasor,
'selPage', pageIndex + 1);
};
})
I've created a forked Plunker that shows how this works (and this solution actually works): http://plnkr.co/edit/2aqCUAFUwwXuGQHpuooj

Angular js comparison

I have a condition that needs to be checked in my view: If any user in the user list has the same name as another user, I want to display their age.
Something like
<div ng-repeat="user in userList track by $index">
<span class="fa fa-check" ng-if="user.isSelected"></span>{{user.firstName}} <small ng-if="true">{{'AGE' | translate}} {{user.age}}</small>
</div>
except I'm missing the correct conditional
You should probably run some code in your controller that adds a flag to the user object to indicate whether or not he/she has a name that is shared by another user.
You want to minimize the amount of logic there is inside of an ng-repeat because that logic will run for every item in the ng-repeat each $digest.
I would do something like this:
controller
var currUser, tempUser;
for (var i = 0; i < $scope.userList.length; i++) {
currUser = $scope.userList[i];
for (var j = 0; j < $scope.userList.length; j++) {
if (i === j) continue;
var tempUser = $scope.userList[j];
if (currUser.firstName === tempUser.firstName) {
currUser.showAge = true;
}
}
}
html
ng-if='user.showAge'
Edit: actually, you probably won't want to do this in the controller. If you do, it'll run every time your controller loads. You only need this to happen once. To know where this should happen, I'd have to see more code, but I'd think that it should happen when a user is added.
You can simulate a hashmap key/value, and check if your map already get the property name. Moreover, you can add a show property for each objects in your $scope.userList
Controller
(function(){
function Controller($scope) {
var map = {};
$scope.userList = [{
name:'toto',
age: 20,
show: false
}, {
name:'titi',
age: 22,
show: false
}, {
name: 'toto',
age: 22,
show: false
}];
$scope.userList.forEach(function(elm, index){
//if the key elm.name exist in my map
if (map.hasOwnProperty(elm.name)){
//Push the curent index of the userList array at the key elm.name of my map
map[elm.name].push(index);
//For all index at the key elm.name
map[elm.name].forEach(function(value){
//Access to object into userList array with the index
//And set property show to true
$scope.userList[value].show = true;
});
} else {
//create a key elm.name with an array of index as value
map[elm.name] = [index];
}
});
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
HTML
<body ng-app="app" ng-controller="ctrl">
<div ng-repeat="user in userList track by $index">
<span class="fa fa-check"></span>{{user.name}} <small ng-if="user.show">{{'AGE'}} {{user.age}}</small>
</div>
</body>

Change DropDownList data with Javascript

I have a page where a user can select if the transaction type is an inter accounts transfer, or a payment.
The model I pass in had two lists.
One is a list of SelectListItem
One is a list of SelectListItem
One of the lists is populated like this:
var entities = new EntityService().GetEntityListByPortfolio();
foreach (var entity in entities.Where(x=>x.EntityTypeId == (int)Constants.EntityTypes.BankAccount))
{
model.BankAccounts.Add(new SelectListItem
{
Value = entity.Id.ToString(CultureInfo.InvariantCulture),
Text = entity.Description
});
}
If the user selects 'Inter account transfer', I need to:
Populate DropdownA with the list from Accounts, and populate DropdownB with the same list of Accounts
If they select "Payment", then I need to change DrowdownB to a list of ThirdParty.
Is there a way, using javascript, to change the list sources, client side?
function changeDisplay() {
var id = $('.cmbType').val();
if (id == 1) // Payment
{
$('.lstSource'). ---- data from Model.ThirdParties
} else {
$('.lstSource'). ---- data from Model.Accounts
}
}
I'd prefer not to do a call back, as I want it to be quick.
You can load the options by jquery Code is Updated
Here is the code
You will get everything about Newton Json at http://json.codeplex.com/
C# CODE
//You need to import Newtonsoft.Json
string jsonA = JsonConvert.SerializeObject(ThirdParties);
//Pass this jsonstring to the view by viewbag to the
Viewbag.jsonStringA = jsonA;
string jsonB = JsonConvert.SerializeObject(Accounts);
//Pass this jsonstring to the view by viewbag to the
Viewbag.jsonStringB = jsonB;
You will get a jsonstring like this
[{"value":"1","text":"option 1"},{"value":"2","text":"option 2"},{"value":"3","text":"option 3"}]
HTML CODE
<button onclick="loadListA();">Load A</button>
<button onclick="loadListB();">Load B</button>
<select name="" id="items">
</select>
JavaScript Code
function option(value,text){
this.val= value;
this.text = text;
}
var listA=[];
var listB=[];
//you just have to fill the listA and listB by razor Code
//#foreach (var item in Model.ThirdParties)
//{
// <text>
// listA.push(new option('#item.Value', '#item.Text'));
// </text>
// }
//#foreach (var item in Model.Accounts)
// {
// <text>
// listA.push(new option('#item.Value', '#item.Text');
// </text>
// }
listA.push(new option(1,"a"));
listA.push(new option(2,"b"));
listA.push(new option(3,"c"));
listB.push(new option(4,"x"));
listB.push(new option(5,"y"));
listB.push(new option(6,"z"));
function loadListA(){
$("#items").empty();
listA.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
function loadListB(){
$("#items").empty();
listB.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
NEW Javascript Code fpor Json
var listA=[];
var listB=[];
var jsonStringA ='[{"val":"1","text":"option 1"},{"val":"2","text":"option 2"},{"value":"3","text":"option 3"}]';
var jsonStringB ='[{"val":"4","text":"option 4"},{"val":"5","text":"option 5"},{"value":"6","text":"option 6"}]';
//you just have to fill the listA and listB by razor Code
//var jsonStringA = '#Viewbag.jsonStringA';
//var jsonStringB = '#Viewbag.jsonStringB';
listA = JSON.parse(jsonStringA);
listB = JSON.parse(jsonStringB);
function loadListA(){
$("#items").empty();
listA.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
function loadListB(){
$("#items").empty();
listB.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
Here is the fiddle http://jsfiddle.net/pratbhoir/TF9m5/1/
See the new Jsfiddle for Json http://jsfiddle.net/pratbhoir/TF9m5/3/
ofcourse you can so that
try
var newOption = "<option value='"+"1"+'>Some Text</option>";
$(".lstSource").append(newOption);
or
$(".lstSource").append($("<option value='123'>Some Text</option>");
Or
$('.lstSource').
append($("<option></option>").
attr("value", "123").
text("Some Text"));
Link for reference
B default, I don't think the concept of "data-source" means something in html/javascript
Nevertheless, the solution you're looking for is something like knockoutjs
You'll be able to bind a viewmodel to any html element, then you will be able to change the data source of your DropDownList
see : http://knockoutjs.com/documentation/selectedOptions-binding.html

Set default value for dropdownlist using angularjs?

I have code that populates then dropdownlist and the javascript variable that gets the last item in the list. Now all I want to do is select that last item as the default .What am I missing ?
<div class="row">
<div>
<select ng-init="lastItem" ng-model="congressFilter" ng-options="cc.congressLongName for cc in ccList"></select>
</div>
<div class="grid-style" data-ng-grid="userGrid">
</div>
ccResource.query(function (data) {
$scope.ccList.length = 0;
angular.forEach(data, function (ccData) {
$scope.ccList.push(ccData);
})
//Set default value for dropdownlist?
$scope.lastItem = $scope.ccList[$scope.ccList.length - 1];
});
You simply need to asign a value to congressFilter in your controller.
$scope.congressFilter = 'someVal';
It depends a little on how your data looks however.
It might help to new developers. need to add default id for display default item in option.
The below code sample we add [ $scope.country.stateid = "4" ] in controller $scope to set the default.
var aap = angular.module("myApp", []);
aap.controller("MyContl", function($scope) {
$scope.country = {};
$scope.country.stateid = "4";
$scope.country.states = [{
id: "1",
name: "UP"
}, {
id: "4",
name: "Delhi"
}];
});
<body ng-app="myApp">
<div ng-controller="MyContl">
<div>
<select ng-model="country.stateid" ng-options="st.id as st.name for st in country.states">
</select>
ID : {{country.stateid}}
</div>
</div>
</body>

Categories