Angularjs - Set default option in select with dynamic ng-model - angularjs

I have this problem: i created a selects inside a ng-repeat, the ng-model of each select is dinamically generated.
I need to set a default value to these selects, but i don't know how i can do this
HTML
<div ng-controller="ricercaAttivita">
<div class="accordion-group" ng-repeat="masterAttribute in masterAttributes">
<select class="trip dark" ng-change = "search(1, true, true)" ng-model="masterAttribute.Id" ng-options="attr.Id as attr.Value for attr in masterAttribute.Values">
<option value="">Tutte</option>
</select>
</div>
</div>
APP.JS
var tantoSvagoApp = angular.module('tantoSvagoApp');
tantoSvagoApp.controller("ricercaAttivita", function ($scope) {
$scope.masterAttributes = {"id" : "11", nome" : "MARCHE", "values" :
[{ "id": "114", "nome": "ANCONA" }, { "id": "116", "nome": "ASCOLI PICENO" }]
},
{"id" : "12", nome" : "LOMBARDIA", "values" :
[{ "id": "120", "nome": "MILANO" }, { "id": "121", "nome": "BERGAMO" }]
};
});
The ng-model of my select is "masterAttribute.Id", i need to loop every generated select and, in certain conditions, set a particular default option selected.
Something like
$scope.masterAttribute.Id = value;
How i can do this?
Anyone can hel me PLEASE?

just set the selected value object to $scope.masterAttribute. In your controller add
$scope.masterAttribute = masterAttribute.Values[0];
hope this will help.

$scope.masterAttributes should be an array [],
$scope.masterAttributes=[{
"id": "11",
nome " : "
MARCHE ", "
values " : [{
"id": "114",
"nome": "ANCONA"
}, {
"id": "116",
"nome": "ASCOLI PICENO"
}]
},
{
"id": "12",
nome " : "
LOMBARDIA ", "
values " : [{
"id": "120",
"nome": "MILANO"
}, {
"id": "121",
"nome": "BERGAMO"
}]
And finally set default value in select is,
$scope.masterAttribute = $scope.masterAttributes[0].values[0];

Related

rxjs/Angular2 Loop but show different object of a single associative array

I recently combined two array using rxjs
MyArray = [{
"Field": ["Cars"],
"Type": ["BMW", "Toyota", "Volvo"]
},
{
"Field": ["House"],
"Type": ["Condominium", "TownHouse"],
}
PriceArray = [
{
field: Cars,
distribution: [{"name" : "BMW","price":2},{"name" : "Toyota","price":3}]
},
{
field: People,
distribution: [{"name" : "Condominium","price":3},{"name" : "TownHouse","price":2}]
}]
using rxjs filter
const $MergeData = MyArray.map(val => {
return Object.assign({}, val,this.PriceArray.filter(v => v.Field === val.field)[0])
});
this.mergedArray = $MergeData;
Now it looked this..
mergedArray = [{
"Field": "Cars",
"Type": ["BMW", "Toyota", "Volvo"],
"field" : "Cars",
"distribution" : [
{
"name" : "BMW"
"price": 2 ,
},
{
"name" : "Toyota"
"price": 3 ,
},
{
"name" : "Toyota"
"price": 4 ,
}
]
}, .... (house array here)];
Then I tried to show the item price but its not working
<div *ngFor="let item of mergedArray">
<div *ngFor="let car of item.Field; let i = index">
<p>{{car}} </p>
<p>{{item.distribution.price[i]}} </p>
</div>
</div>
I am hoping for a fix or better if the array should look like this instead
mergedArray = [{
"Field": "Cars",
"Type": ["BMW": 2, "Toyota" : 3, "Volvo" : 4],
}]
Hoping it would me possible as it is much easier to loop.
I think that this is the desired effect, also keep in mind that when using Array.prototype.filter and no elements pass the test the returned value will be [] and if you try to access the [][0] element, the value will be undefined, after that if you try to access some property from that undefined value, it will throw an error.
For example if you try to access the price of Volvo it will throw an error Cannot read property 'price' of undefined, because Volvo doesn't exist in the PriceArray
let priceArray = [
{
"name" : "BMW",
"price": 2
},
{
"name" : "Toyota",
"price": 3
},
{
"name" : "Toyota",
"price": 4
}
];
let myArray = [{
"Field": "Cars",
"Type": ["BMW", "Toyota", "Volvo"]}]
let findPrice= (priceArray,mark)=> priceArray
.find(x=> x.name === mark)
? priceArray.find(x=> x.name === mark).price
: 'No data'
let mergedArray = myArray[0].Type.map(x=> ({[x]:findPrice(priceArray,x)}))
console.log(mergedArray)

Angular pre-select multiple values in Multi Select field

Trying to pre-select multiple values in my selectfield.
My HTML
<select multiple
data-ng-options="e.id for e in myElements"
data-ng-model="mySelect">
</select>
Put data in the select box (works fine)
var elements = [
{ "id": "AAA" },
{ "id": "BBB" },
{ "id": "CCC" },
{ "id": "DDD" },
{ "id": "EEE" },
{ "id": "FFF" },
{ "id": "GGG" }
]
$scope.myElements = elements;
This does NOT work
var preselected = [
{ "id": "BBB" },
{ "id": "DDD" },
{ "id": "FFF" }
]
$scope.mySelect = preselected;
This does NOT work
var preselected = [ "BBB", "DDD", "FFF" ]
$scope.mySelect = preselected;
Anyone got any ideas?
You have two options:
1- Use as and track by if you want objects as selected values (PLUNKER)
ng-options="e as e.id for e in vm.elements track by e.id"
HTML
<select multiple
ng-options="e as e.id for e in vm.elements track by e.id"
ng-model="vm.selecetedValues">
</select>
CONTROLLER
function MainCtrl() {
var vm = this;
vm.elements = [{ "id": "AAA" },{ "id": "BBB" },{ "id": "CCC" }];
vm.selectedValues = [
{ "id": "AAA" },
{ "id": "CCC" }
];
}
2- Only Use as syntax if you want strings or numbers as selected values (PLUNKER)
ng-options="e.id as e.name for e in elements"
first argument e.id is the value of selected option
second argument e.name is the displayed value
In your case: ng-options="e.id as e.id for e in elements"
HTML
<select multiple
ng-options="e.id as e.id for e in vm.elements"
ng-model="vm.selecetedValues">
</select>
CONTROLLER
function MainCtrl() {
var vm = this;
vm.elements = [{ "id": "AAA" },{ "id": "BBB" },{ "id": "CCC" }];
vm.selectedValues= [
"BBB",
"DDD"
];
}

What would be angular ng-option equivalent of this select?

I am struggling to get this into an ng-option. Is it even possible?
<select ng-model="detail_type_id">
<optgroup ng-repeat="type in data.detailTypes" label="{{type.name}}">
<option ng-repeat="t in type.children" value="{{t.id}}">{{t.name}}</option>
</optgroup>
</select>
DetailTypes looks like this:
[
{"id":7,
"parent_id":null,
"name":"Contact",
"children":[
{"id":8,
"parent_id":7,
"name":"Address",
"children":[]
},
{"id":12,
"parent_id":7,
"name":"Something else",
"children":[]
}
]},
{"id":16,
"parent_id":null,
"name":"Other",
"children":[
{"id":10,
"parent_id":16,
"name":"Remarks",
"children":[]}
]
}
]
Child id needs to be selected. Nesting cannot be deeper.
The ngOptions directive does not work with multidimensional objects. So you need to flatten your array to use it.
I wrote a filter for that:
app.filter('flatten' , function(){
return function(array){
return array.reduce(function(flatten, group){
group.children.forEach(function(child){
child.groupName = group.name;
flatten.push(child)
})
return flatten;
},[]);
}
})
And the HTML part would be like this:
<select ng-model="detail_type_id"
ng-options="item.id as item.name
group by item.groupName for item
in data.detailTypes | flatten track by item.id">
</select>
Plunker (version #1 with filter):
https://plnkr.co/edit/dxi7j8oxInv2VRJ1aL7F
I also modified your object to be like this:
[{
"id": 7,
"parent_id": null,
"name": "Contact",
"children": [{
"id": 8,
"parent_id": 7,
"name": "Address",
"children": []
}, {
"id": 12,
"parent_id": 7,
"name": "Something else",
"children": []
}]
}, {
"id": 16,
"parent_id": null,
"name": "Other",
"children": [{
"id": 10,
"parent_id": 16,
"name": "Remarks",
"children": []
}]
}]
EDIT:
After suggestion I wrote another version without the filter, but flattening the array inside the controller.
Additional Controller JS:
$scope.flattenDetailTypes = flattenDetailTypes($scope.data.detailTypes);
function flattenDetailTypes(array){
return array.reduce(function(flatten, group){
group.children.forEach(function(child){
child.groupName = group.name;
flatten.push(child)
})
return flatten;
},[]);
}
Markup:
<select ng-model="detail_type_id"
ng-options="item.id as item.name group by item.groupName for item in flattenDetailTypes track by item.id"></select>
Plunker (version #2 without filter):
https://plnkr.co/edit/D4APZ6

Angular JS Order By Filter not working for dynamic predicates

I am creating a Grid Control in Angular JS. ( I don't want to use ng-grid, smart table, etc for some reason)
Plunkr URL : http://plnkr.co/edit/arkCZcfXTIsW7sFCxisn?p=preview
On top of the table generated, i have populated fields in the combobox so that user is allowed to search on specific columns
or as free search.
As I see From here :
https://docs.angularjs.org/api/ng/filter/filter
For free search, I have used the syntax as {$:Value} and for column based search, {ColName:Value} syntax
However, I am unable to get it to work when I bind the column names to combobox.
I do get static search to work Eg if I write {'Code':"1"}, this works. but if I take "Code" from a combobox, it doesnt work.
Need help on setting dynamic filter.
This one also does not seem to help.
angular filter with dynamic list of attributes to search
This is the HTML
<div ng-controller="MyGrid">
Search in Column
<select ng-model="FilterByColumn" >
<option value="$">All</option>
<option ng-repeat="hdr in headers | orderBy : hdr.displayOrder" ng-show="hdr.isVisible" value="{{hdr.name}}" >
{{hdr.caption}}
</option>
</select>
Value : <input type="text" ng-model="searchKeyword" />
<br />
Remove Sort
<table>
<thead>
<tr>
<th ng-repeat="hdr in headers | orderBy : hdr.displayOrder" ng-show="hdr.isVisible">
{{hdr.caption}}
</th>
</tr>
</thead>
<tbody>
<%--<tr ng-repeat="dataVal in data | filter: {FilterByColumn : searchKeyword} | orderBy:predicate:reverse "> **Does not work--%>**
<%--<tr ng-repeat="dataVal in data | filter: {$ : searchKeyword} | orderBy:predicate:reverse "> **This works--%>**
<tr ng-repeat="dataVal in data | filter: GetFilter (FilterByColumn, searchKeyword) | orderBy:predicate:reverse "> **<!-- Does not work -->**
<td ng-repeat="hdr in headers | orderBy : hdr.displayOrder" ng-show="hdr.isVisible">
{{dataVal[hdr.name]}}
</td>
</tr>
</tbody>
</table>
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}} ; SearchBy = {{FilterByColumn}} ; Search Key : {{searchKeyword}} </pre>
</div>
This is the JS :
'use strict';
var MyApp = angular.module('MyApp', []);
MyApp.controller('MyGrid', function ($scope) {
$scope.predicate = 'Code';
$scope.reverse = false;
$scope.FilterByColumn = '$';
$scope.headers = [
{
"name": "Code",
"caption": "Code",
"isVisible": true,
"displayOrder": 12
},
{
"name": "DispName",
"caption": "My Name",
"isVisible": true,
"displayOrder": 1
},
{
"name": "Locked",
"caption": "Islocked",
"isVisible": true,
"displayOrder": 2
}
];
$scope.data =
[{
"Code": "1",
"DispName": "abdul",
"Locked": "0"
},
{
"Code": "2",
"DispName": "Hemant",
"Locked": "0"
},
{
"Code": "3",
"DispName": "Rahul",
"Locked": "0"
},
{
"Code": "4",
"DispName": "Sandy",
"Locked": "0"
},
{
"Code": "5 ",
"DispName": "Nihal",
"Locked": "0"
},
{
"Code": "6",
"DispName": "Sachin",
"Locked": "0"
},
{
"Code": "7",
"DispName": "abdul f",
"Locked": "0"
},
{
"Code": "8",
"DispName": "abdul g",
"Locked": "0"
},
{
"Code": "9",
"DispName": "abdul h ",
"Locked": "0"
},
{
"Code": "10",
"DispName": "abdul i",
"Locked": "0"
}
];
$scope.getValue = function (obj, PropName) {
return obj[PropName];
};
$scope.SetSort = function (objName) {
//alert(objName);
$scope.predicate = objName;
$scope.reverse = !$scope.reverse;
};
$scope.GetFilter = function (srchCol, Srchval) {
//alert(srchCol);
//alert(Srchval);
if (srchCol == "") {
return { $: Srchval };
}
else {
return { srchCol: Srchval };
}
};
});
That is because when you write { srchCol: Srchval } - srcCol is the property name and is not substituted with the value in variable srcCol, try this syntax instead:
$scope.GetFilter = function (srchCol, Srchval) {
if (srchCol == "") {
return { $: Srchval };
}
else {
filter = {};
filter[srchCol] = Srchval;
return filter;
}
};

Angular JS orderBy not working using dropdown

i am trying to do orderBy using dropdown value, but its not working :(
CODE:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.datas = [{
"id": "1",
"name": "name area 1"
}, {
"id": "2",
"name": "name area 2"
}, {
"id": "3",
"name": "name area 3"
}, {
"id": "4",
"name": "name area 4"
}];
$scope.dropdown = [{
"title": "Newest first",
"value": "true"
}, {
"title": "Oldest first",
"value": "reverse"
}];
});
HTML:
<div ng-app="myApp">
<div ng-controller="myCtrl">
<ul ng-repeat="rows in datas | orderBy: 'id':orderByData">
<li>{{rows.id}} : {{rows.name}}</li>
</ul>
<select ng-model="orderByData" ng-options="x.value as x.title for x in dropdown"></select>
</div>
</div>
DEOM JS BIN
Why you use reverse?
Please use false instead reverse and it should work fine.
$scope.dropdown = [{
"title": "Newest first",
"value": "true"
}, {
"title": "Oldest first",
"value": "false"
}];
You don't need reverse parameter here. Instead you can do something like this:
<ul ng-repeat="rows in datas | orderBy: getSort()">
<li>{{rows.id}} : {{rows.name}}</li>
</ul>
Where getSort is defined as:
$scope.getSort = function() {
return $scope.orderByData ? 'id' : '-id';
};
Basically you want sort part to look like orderBy: 'id' or orderBy: '-id'.
Demo: http://jsbin.com/pepureta/1/edit?html,js,output

Resources