How to make first option selected in chosen select - angularjs

I have chosen select, and my options gets by ng-model and ng-options. How I can make 1-st option selected when page is loaded?
<select chosen data-placeholder="Choose a project..."
ng-model="workflow.ProjectID"
ng-model-options="{ updateOn: 'blur' }"
ng-change="addActionButtons()"
ng-options="item.Id as item.Name for item in projectList">
<option value=""></option>
</select>
This is controller:
$scope.bindModel = function(data) {
$scope.model = data;
$scope.projectList = Global.projectList;
$scope.Task.push($scope.newTask());
};
$scope.Task = [];
$scope.newTask = function() {
return {
ProjectId: $scope.workflow.ProjectID = $scope.projectList[0].Id,
Date: getDate(),
TaskDescription: '',
TimeWorked: '1',
Note: '',
isSaved: false
};
};

You can use ng-init
Use
ng-init="workflow.ProjectID = projectList[0]['Id']"

On your controller, you have to put something like this :
//If workflow is never use in your controller, you have to declare it before
$scope.workflow = {};
$scope.workflow.ProjectID = $scope.projectList[0].Id;

You can try something like this :
//init list select
$scope.values = [{ id: 1, label: '1' }, { id: 2, label: '2' }, { id: 3, label: '3' }, { id: 10, label: '10' }, { id: 20, label: '20' }];
// in your html ng-init select the first items in values
<select ng-options="item.label for item in values track by item.id" ng-model="selected" ng-change="changeNumPerPage(selected)" ng-init="selected = values[0]"></select>

Related

Filter and auto selected dropdown angularjs

I am new to angularjs and still learning things. I have this code below. What I am aiming here is to load the data into the dropdown from the database. For example the data from the database is New Construction I want to load all data from LoadDropdown function and the New Construction is selected as default.
HTML
<select name="ScopeofWork" class="form-control" ng-model="drpScopeWork" ng-options="SoW as SoW.label for SoW in ScopeOfWorkList">
<option value="" selected hidden></option>
</select>
JS
function LoadDropdown() {
$scope.ScopeOfWorkList = [{ value: 'New Construction', label: 'New Construction' },
{ value: 'Erection', label: 'Erection' },
{ value: 'Addition', label: 'Addition' },
{ value: 'Renovation', label: 'Renovation' },
{ value: 'Repair', label: 'Repair' }];
}
fnLoadDropdown();
function fnLoadDropdown() {
var url = '/AccessoryGroundPreparation/LoadScopeofWork';
$http({
method: "post",
url: url,
//data: { "ScopeOfWork": ScopeOfWork, "projectID": projectID }
}).then(function (res) {
var data = res.data;
if (data.data == null)
LoadDropdown();
else {
// $scope.drpScopeWork = $scope.ScopeOfWorkList[0];
$scope.drpScopeWork = data.data;
}
});
}
Use ng-init to assign a value to your model drpScopeWork form 0 index of your array like ng-init="drpScopeWork = ScopeOfWorkList[0].value"
Here is working code snippet:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.ScopeOfWorkList = [{
value: 'New Construction',
label: 'New Construction'
},
{
value: 'Erection',
label: 'Erection'
},
{
value: 'Addition',
label: 'Addition'
},
{
value: 'Renovation',
label: 'Renovation'
},
{
value: 'Repair',
label: 'Repair'
}
];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<select name="ScopeofWork" class="form-control" ng-model="drpScopeWork" ng-options="SoW.value as SoW.label for SoW in ScopeOfWorkList" ng-init="drpScopeWork = ScopeOfWorkList[0].value">
</select>
</div>
</div>

AngularJS: empty option rendering when showing multiple values in ng-options

I am trying to use ng-options for displaying multiple values in the drop down.
When displaying only one value, it works fine but not when displaying multiple values.
Here is my code.. http://tpcg.io/QrjgXN
Controller:
app.controller('listController', function() {
var vm = this;
vm.gradeList = [{
grade: 1,
category: 'very poor'
},
{
grade: 2,
category: 'poor'
},
{
grade: 3,
category: 'average'
},
{
grade: 4,
category: 'good'
},
{
grade: 5,
category: 'very good'
}];
vm.gradeSelected = vm.gradeList[0].grade;
});
HTML:
<select multiple class="form-control"
ng-selected="vm.gradeSelected"
ng-model="vm.gradeSelected"
ng-options="gradeObj.grade + ' (' + gradeObj.category + ')' for gradeObj in vm.gradeList">
</select>
What else is missing?
You can just change your select tag as below to be able to display the selected value.
<select class="form-control"
ng-model="vm.gradeSelected">
<option ng-repeat="gradeObj in vm.gradeList" ng-selected="vm.gradeSelected" ng-value="{{gradeObj.grade}}"> {{gradeObj.grade}} - {{gradeObj.category}}</option>
</select>
DEMO
var app = angular.module('myApp', []);
app.controller('listController', function() {
var vm = this;
vm.gradeList = [{
grade: 1,
category: 'very poor'
},
{
grade: 2,
category: 'poor'
},
{
grade: 3,
category: 'average'
},
{
grade: 4,
category: 'good'
},
{
grade: 5,
category: 'very good'
}];
vm.gradeSelected = vm.gradeList[0].grade;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="listController as vm">
<select class="form-control" ng-model="vm.gradeSelected">
<option ng-repeat="gradeObj in vm.gradeList" ng-selected="vm.gradeSelected" ng-value="{{gradeObj.grade}}"> {{gradeObj.grade}} - {{gradeObj.category}}</option>
</select>
</div>
When selecting multiple items, the model needs to be initialized to an array:
<select multiple class="form-control"
̶n̶g̶-̶s̶e̶l̶e̶c̶t̶e̶d̶=̶"̶v̶m̶.̶g̶r̶a̶d̶e̶S̶e̶l̶e̶c̶t̶e̶d̶"̶
ng-model="vm.gradeSelected"
ng-options="gradeObj.grade as vm.desc(gradeObj) for gradeObj in vm.gradeList">
</select>
̶v̶m̶.̶g̶r̶a̶d̶e̶S̶e̶l̶e̶c̶t̶e̶d̶ ̶=̶ ̶v̶m̶.̶g̶r̶a̶d̶e̶L̶i̶s̶t̶[̶0̶]̶.̶g̶r̶a̶d̶e̶;̶
vm.gradeSelected = [vm.gradeList[0].grade];
vm.desc = item => item.grade + ' (' + item.category + ')';
The DEMO
angular.module("app",[])
.controller('ctrl', function() {
var vm = this;
vm.gradeList = [{
grade: 1,
category: 'very poor'
},
{
grade: 2,
category: 'poor'
},
{
grade: 3,
category: 'average'
},
{
grade: 4,
category: 'good'
},
{
grade: 5,
category: 'very good'
}];
vm.gradeSelected = [vm.gradeList[0].grade];
vm.desc = item => item.grade + ' (' + item.category + ')';
});
select {
height: 100px;
}
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl as vm">
<select multiple class="form-control"
ng-model="vm.gradeSelected"
ng-options="gradeObj.grade as vm.desc(gradeObj) for gradeObj in vm.gradeList">
</select>
<br>
gradeSelected = {{vm.gradeSelected}}
</body>
Also the ng-selected directive does not work with ng-model, see
When select have ng-model attribute, ng-selected not working
UPDATE
if I remove the multiple attribute, the demo does not work
If you remove the multiple attribute, don't initialize with an array:
<select ̶m̶u̶l̶t̶i̶p̶l̶e̶ class="form-control"
ng-model="vm.gradeSelected"
ng-options="gradeObj.grade as vm.desc(gradeObj) for gradeObj in vm.gradeList">
</select>
̶v̶m̶.̶g̶r̶a̶d̶e̶S̶e̶l̶e̶c̶t̶e̶d̶ ̶=̶ ̶[̶v̶m̶.̶g̶r̶a̶d̶e̶L̶i̶s̶t̶[̶0̶]̶.̶g̶r̶a̶d̶e̶]̶;̶
vm.gradeSelected = vm.gradeList[0].grade;
vm.desc = item => item.grade + ' (' + item.category + ')';
With the multiple attribute, the ng-model takes and returns an array; without, a single value.
From the Docs:
multiple (optional)
Allows multiple options to be selected. The selected values will be bound to the model as an array.
— AngularJS <select> Directive API Reference

selected option is not getting displayed Angularjs dropdownlist

When I am using an object where I have property which has selectedOptions it is not getting displayed in the dropdownlist. However, when I put in scope and select from the object then it displayed. Anyone has any idea why the first one is not working. Here is the plunker link.
http://plnkr.co/edit/XLuXmAmh4F9OobyJhBCW?p=preview
var app = angular.module('angularjs-starter', []);
var model = {
options : [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 3, name: 'blah' }],
selectedOption : { id: 1, name: 'foo' }
}
app.value('vm',model);
app.controller('MainCtrl', function($scope,vm) {
$scope.vm =vm;
$scope.items = [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 3, name: 'blah' }];
$scope.selectedItem = $scope.items[1];
});
<body ng-controller="MainCtrl">
<h1>Select something below</h1>
<select id="s1" ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
<h3>The selected item:</h3>
<pre>{{selectedItem | json}}</pre>
<h3>The inner html of the select:</h3>
<pre id="options" class="prettify html"></pre>
<select data-ng-options="o.name for o in vm.options" data-ng-model="vm.selectedOption"><option value="">Select one</option></select>
<pre>{{vm.selectedOption | json}}</pre>
</body>
Angular uses strict comparison (===) to evaluate if given option is to be selected. It will only if the value of selectedItem is the same as the option's one. And in JavaScript, if you create two objects of the same structure and try to strictly compare it, they are not the same, i.e.:
{a: 1} !== {a: 1}
In the second example you're keeping the reference to the original object insted, so it would be like doing this:
var obj1 = {a: 1};
var obj2 = obj1;
obj1 === obj2;

Repeating multidimensional array object in angular

I have an array that looks like this:
[Object{ 82893u82378237832={ id=8, no=1, type="event", name="Sample1"}}, Object{ 128129wq378237832={ id=9, no=1, type="event", name="Sample2"}} ]
Now ignoring the first part which is just a random token i want to get the array inside that. i.e. id,no,type,name and display them in an ng-repeat, how can i achieve this?
This is how i create the above array:
var obj = {};
obj[data.responseData] = {
id: 8,
no: 1,
type: 'event',
name: ''
}
$scope.items.push(obj);
Your example doesn't include an array.
Anyway here's a good example.
Use map to transform an array to another array and use ng-repeat in a similar way that I've done.
Html:
<div ng-app="app">
<div ng-controller="ctrl">
<div ng-repeat="item in myArr">
{{item}}
</div>
</div>
</div>
JS:
angular.module('app', []).
controller('ctrl', function ($scope) {
var arr = [{
myId: '82893u82378237832',
id: 8,
no: 1,
type: "event",
name: "Sample1"
}, {
myId: '128129wq378237832',
id: 9,
no: 1,
type: "event",
name: "Sample2"
}];
// mapped the new object without myId
$scope.myArr = arr.map(function (item) {
return {
id: item.id,
no: item.no,
type: item.type,
name: item.name
}
});
});
JSFIDDLE.

exact filter in angular

In Angular, is there a way to modify the filter such that it only returns exact matches?
Example:
var words = [
{ title: "ball" },
{ title: "wall" },
{ title: "all" },
{ title: "alloy" }
];
var wordsFiltered = filter('filter')
(
words,
{
'title': 'all'
}
);
The above will match 'ball', 'wall', 'all' and 'alloy'. But I would like it to only match 'all'. Any way to change it?
UPDATE
Starting from AngularJS v.1.1.3 the exact filtering is provided natively:
Find words that exactly match title:
<input ng-model="match.title" />
<br>
and exactly match type:
<input ng-model="match.type" />
<hr>
<table>
<tr ng-repeat="word in words | filter:match:true">
<td>{{word.title}}</td>
</tr>
</table>
Plunker
Your question implies that you would want to match against multiple object properties so here's a filter that does that:
app.controller('AppController',
[
'$scope',
function($scope) {
$scope.match = {};
$scope.words = [
{ title: "ball", type: 'object' },
{ title: "wall", type: 'object' },
{ title: "all", type: 'word' },
{ title: "alloy", type: 'material' }
];
}
]
);
app.filter('exact', function(){
return function(items, match){
var matching = [], matches, falsely = true;
// Return the items unchanged if all filtering attributes are falsy
angular.forEach(match, function(value, key){
falsely = falsely && !value;
});
if(falsely){
return items;
}
angular.forEach(items, function(item){ // e.g. { title: "ball" }
matches = true;
angular.forEach(match, function(value, key){ // e.g. 'all', 'title'
if(!!value){ // do not compare if value is empty
matches = matches && (item[key] === value);
}
});
if(matches){
matching.push(item);
}
});
return matching;
}
});
<body ng-controller="AppController">
Find words that exactly match title:
<input ng-model="match.title" />
<br>
and exactly match type:
<input ng-model="match.type" />
<hr>
<table>
<tr ng-repeat="word in words | exact:match">
<td>{{word.title}}</td>
</tr>
</table>
</body>
PLUNKER
Try this :
var words = [
{ title: "ball" },
{ title: "wall" },
{ title: "all" },
{ title: "alloy" }
];
var wordsFiltered = filter('filter')
(
words,
{
'title': 'all'
},
true
);
You can use Regex to achieve a simple implementation:
<input ng-model="query" />
<tr ng-repeat="word in words | filter: myFilter">
In the controller:
$scope.myFilter = function (word) {
if ($scope.query === '') return true;
var reg = RegExp("^" + $scope.query + "$");
return reg.test(word.title);
};
I would create a new filter. Is this what you want?
HTML
<div ng-controller="MyCtrl">
{{words | exactMatch:'all'}} !
</div>
JavaScript
var myApp = angular.module('myApp',[]);
myApp.filter('exactMatch', function() {
return function(words, pattern) {
var result = [];
words.forEach(function (word) {
if (word.title === pattern) {
result.push(word);
}
});
return result;
}
});
function MyCtrl($scope) {
$scope.words = [
{title: "ball", other: 1},
{title: "wall", other: 2},
{title: "all", other: 3},
{title: "alloy", other: 4},
{title: "all", other: 5},
];
}
JsFiddle: jsfiddle
More information about custom filters: filters, creating custom filters and using filters
If you want use filter in Javascript instead of html you should look here: jsfiddle
I created my own filter.
<select
ng-model="selection.neType"
ng-options="option.NE_TYPE_ID as option.NAME for option in networkElementTypes">
<option value="">Todos</option>
</select>
<select
ng-model="selection.neTypeVendor"
ng-options="option.VENDOR_TYPE_ID as option.NAME for option in networkElementTypeVendors | exactMatch: {FK_NE_TYPE_ID: selection.neType}">
<option value="">All</option>
</select>
app.filter('exactMatch', function() {
return function(elements, pattern) {
var result = [];
var fieldSearch = Object.keys(pattern)[0];
elements.forEach(function (element) {
if (element[fieldSearch] == pattern[fieldSearch]) {
result.push(element);
}
});
return result;
}
});
angular-filter is a useful library of filters.
One of their filters is the where filter that does an exact match.

Resources