how to set initial value to combobox in angular? - javascript

If I want to set the value of the combobox I have tried this:
controllercode:
$scope.streettypeMockData = [{
name: 'Street',
value: 'Street'
}, {
name: 'Avenue'
}, {
name: 'Crescent'
}, {
name: 'Drive'
}, {
name: 'Road'
}, {
name: 'Highway'
}];
var sel = "Street";
var selectedValue = {
name: sel
};
$scope.streetTypeSelected = selectedValue;
Can anyone tell me why this does not work? see also http://plnkr.co/edit/4ISL8A1cNGCtafsc0leX?p=preview

The code has a few issues:
The ng-options select the name, while the ng-model points to an object. Better use streetType as streetType.name for streetType in streettypeMockData to select the entire object.
In this case, the initial value will not be honoured because Angular will try to compare objects by reference; use track by.
The full <select> should be:
<select class="form-control" ng-model="streetTypeSelected"
ng-options="streetType as streetType.name for streetType in streettypeMockData track by streetType.name">
See forked plunker.

You can simple use ng-init like this
<select ng-init="streetTypeSelected = streettypeMockData[0]" class="form-control" ng-model="streetTypeSelected" ng-options="streetType.name for streetType in streettypeMockData">
</select>
Working Demo
Also you can do Like as shown below
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.streettypeMockData = [
{name: 'Street', value: 'Street'},
{name: 'Avenue'},
{name: 'Crescent'},
{name: 'Drive'},
{name: 'Road'},
{name: 'Highway'}
];
$scope.streetTypeSelected = $scope.streettypeMockData[0];
});
Working Demo
Also take a look at this
https://docs.angularjs.org/api/ng/directive/select

Related

Angular equivalent of index() from jquery

I use Angular 1.5. I have two selects and I need to update 2nd select depending on the index of the option of 1st select.
Is there an easy way to get the index of option selected? Like from 0 to 5.
My 1st select is :
<select class="form-control" name="idEtablissement" ng-model="infosEtab.idEtablissement" ng-change="updateContrats()"
ng-options='item.id as item.name for item in listeEtablissement'>
</select>
I need something like that :
// return -1, listeEtablissement is [{id: 2, name: 'Test'}, {...}]
alert($scope.listeEtablissement.indexOf($scope.infosEtab.id));
$listeEtablissement is :
[{id: 2, name: 'Test'}, {id: 5, name: 'Test 2'}]
But I need to have the index, like 0 or 1.
EDITED
Ok I'll use Javascript approach, the most simple one :
$scope.updateContrats = function() {
var index = document.getElementById('idEtablissement').selectedIndex;
// ....
}
You should do it by native JavaScript using array.findIndex(); like in this runnable demo fiddle.
MDN reference of array.findindex()
View
<div ng-controller="MyCtrl">
<select class="form-control"
name="idEtablissement"
ng-model="infosEtab.idEtablissement"
ng-change="updateContrats()"
ng-options='item.id as item.name for item in listeEtablissement'>
</select>
</div>
AngularJS Application
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.selectedIndex = null;
$scope.listeEtablissement = [{
id: 2,
name: 'Test'
}, {
id: 5,
name: 'Test 2'
}];
$scope.updateContrats = function() {
$scope.selectedIndex = $scope.listeEtablissement.findIndex(function(item) {
return item.id === $scope.infosEtab.idEtablissement
});
}
});
Change
ng-options
to
index as item.name for (index, item) in listeEtablissement

ng-options model bind based on property

Hi I am quite new to angular programming and I had a question on angular's ng-options.
I have an object structure like
TestObj: { name: 'Name1', subNames: ['Subname1'] }
TestArr:
[{ name: 'Name1', subNames: ['Subname1'] },
{ name: 'Name2', subNames: ['Subname1'] },
{ name: 'Name3', subNames: ['Subname1'] }]
And I am trying to use ng-options to bind one of the TestArr objects to TestObj.
<select class="touchpoint-settings-create-channel-box ng-model="TestObj" ng-options="curTest.name for curTest in TestArr"></select>
However, is there any way to make TestObj bind to the object in TestArr that has the same 'name' property?
This jsfiddle is a good example of what I mean. http://jsfiddle.net/KN9xx/840/
When it first starts up, selectedPerson is set to an object similar to the first item in the array, but ng-options does not realize it is the same object.
Thank you
I would not recommend following the example in that jsfiddle. Essentially, you do not want TestObj AND TestArr. If TestObj is not just a reference to TestArr, they are not going to be the same object and you're duplicating data because Angular and JavaScript do not recognize that the two objects have the same keys and values when they are separate objects.
You should follow the example in this SO post: How to have a default option in Angular.js select box
Rather than using TestObj like you are, use ng-init to set the default value.
var TestArr =
[{ name: 'Name1', subNames: ['Subname1'] },
{ name: 'Name2', subNames: ['Subname1'] },
{ name: 'Name3', subNames: ['Subname1'] }];
<select
class="touchpoint-settings-create-channel-box
ng-init="TestObj = options[0]"
ng-model="TestObj"
ng-options="option.name for option in TestArr">
</select>
To illustrate my point on objects:
var obj1 = { name: 'Me' };
var obj2 = { name: 'Me' };
While obj1 and obj2 look exactly the same, the variables are just references to the underlying object, not the values, and the JS interpreter doesn't know that I intend both of those objects to be the same. However, if you strings or numbers, it works like you expect.
var me = 'Me';
var stillMe = 'Me';
console.log(obj1 === obj2); // prints false
console.log(me === stillMe); // prints true

I can not show the value in angular select

This is the code HTML:
<div ng-controller="SelectCtrl">
<p>selected item is : {{selectedItem}}</p>
<p> age of selected item is : {{selectedItem.age}} </p>
<select ng-model="selectedItem" ng-options="item.name for item in items">
</select>
</div>
This is the code JavaScript:
var app = angular.module('myApp', []);
app.controller('SelectCtrl', function($scope) {
$scope.items = [{name: 'one', age: 30 },{ name: 'two', age: 27 },{ name: 'three', age: 50 }];
console.log($scope.selectedItem); //this is undefined :(
});
I want to show the selected value in the controller, but apparently it is undefined.
what is the correct way?
#JoshLeeDucks is correct. $scope.selectedItem is not defined on the scope when you are attempting to log its value. When the user assigns the property a value by selecting an element in the <select> input Angular will recognise that selectedItem is not defined and create it.
Log the value using a $watch:
console.log($scope.selectedItem); // undefined
$scope.selectedItem = 'someDefaultValue';
console.log($scope.selectedItem); // 'someDefaultValue'
$scope.$watch('selectedItem', function(newValue) {
console.log(newValue); // whatever `item.name` the user has selected
});
If you want to show the selectedItem in UI or using console.log when page loading. you should initialize the selectedItem value in your controller.
Like:
var app = angular.module('myApp', []);
app.controller('SelectCtrl', function($scope) {
$scope.items = [{name: 'one', age: 30 },{ name: 'two', age: 27 },{ name: 'three', age: 50 }];
$scope.selectedItem = $scope.items[0];
console.log($scope.selectedItem); //this is {name: 'one', age: 30 } :(
});

Angularjs: update select options

I have two select menus . One for country selection and other for state. I need to update states based country selected. I am able to log states but not able to list them in select menu.Please help.
Angular:
angular.module('demoApp', []).controller('DemoController', function($scope) {
$scope.countries = [
{ label: 'Please select', value: 0 },
{ label: 'India', value: 1 },
{ label: 'US', value: 2 }
];
$scope.data = [{'1':[{ label: 'Delhi', value: 0 },{ label: 'Mumbai', value: 1 },{ label: 'Chennai', value: 2 }]},
{'2':[{ label: 'Alabama', value: 3 },{ label: 'Alaska', value: 4 },{ label: 'Arizona', value: 5 }]}];
$scope.vm = {states: []};
$scope.updateStates = function(countryCode){
$scope.vm.states = $scope.data[countryCode-1];
console.log($scope.vm.states);
};
$scope.correctlySelected = $scope.countries[0];
});
HTML:
<body ng-app="demoApp">
<div ng-controller="DemoController">
<select ng-model="correctlySelected" ng-change="updateStates(correctlySelected.value)" ng-options="opt as opt.label for opt in countries">
</select>
<select ng-options="opt as opt.label for opt in vm.states">
</select>
</div>
</body>
JS Bin:
http://jsbin.com/pafosewedo/1/edit?html,js,console,output
You need to add ng-model to your states <select> - this is required when you are using ng-options
You also have an inconvenient model for the states data. Each element of the data array that corresponds to the country's states is an object with a changing key whose value is an array of states. You could make it work, but it's better to change it to something more reasonable:
$scope.data = {
1: [{ label: 'Delhi', value: 0 }, {...}, ],
2: [{...}, {...}, ] // same for US
}
Then it would work with how you specified your ng-options for states, and you wouldn't have to deal with indices:
$scope.updateStates = function(countryCode){
$scope.vm.states = $scope.data[countryCode]; // access by property
};
I think, that you should use some filter like that if you don't want to change your model:
.filter('stateFilter', function() {
return function(states, countryID) {
var filtered = [];
angular.forEach(states, function(state){
if(state.value === countryID)
filtered.push(state);
});
return filtered;
};
});
to filter out all values that have value equal to selected country.value in first select control.
To use that filter you need to modify your ng-repeat directive value in state select control:
ng-options="state as state.label for data | stateFilter:correctlySelected"
I came up with the following solution, view my JSBin
This solutions works by setting the countryCode in the scope when we are updatingStates.
$scope.updateStates = function(countryCode){
$scope.countryCode = countryCode;
$scope.vm.states = $scope.data[countryCode-1];
console.log($scope.vm.states[countryCode]);
};
This change is then reflected in the view.
<select>
<option ng-repeat='i in vm.states[countryCode]'> {{i.label}}
</option>
</select>

Angularjs ui-grid Filter from text input field

Maybe somebody can help me with a little problem. I am pretty new in the field of web programming, but I have programming experience.
I would like to develop a small website that uses angularjs and ui-grid. Unfortunately the filtering is not working from external input fields.
Could somebody please tell me where my programming bug is?
The code can be found here: http://plnkr.co/edit/fiA666OzpBqpTrCiuXER?p=preview
var myDummyData = [{name: "Moroni", age: 50},
{name: "Tiancum", age: 43},
{name: "Jacob", age: 27},
{name: "Nephi", age: 29},
{name: "Enos", age: 34}];
var myDummyData2 = [{name: "aTest", age: 50},
{name: "bTest1", age: 43},
{name: "cTest2", age: 27},
{name: "dTest3", age: 29},
{name: "eTest4", age: 34}];
$scope.filterOptions = {
filterText: ''
};
$scope.gridOpts = {
data: myDummyData,
enableFiltering: true,
columnDefs: [
{name: 'Name', field: 'name', enableFiltering: true
, filter: {
term: $scope.filterOptions.filterText //DOES NOT WORK... BUT WHY
}
},
{name: 'Price', field: 'age'}
]
};
$scope.updateData = function(newValue){
//console.log($scope.gridOpts.data);
console.log($scope.gridOpts.columnDefs[0].filter);
$scope.gridOpts.columnDefs[0].filter = {term: newValue};
console.log("Scope nameid set " + $scope.gridOpts.columnDefs[0].filter.term); //is set but no update
//$scope.$apply(); //not possible gives error! WHY??
//$scope.gridOpts.data = myDummyData; //for testing works
};
$scope.swapData = function () {
if ($scope.gridOpts.data === myDummyData) {
$scope.gridOpts.data = myDummyData2;
}
else {
$scope.gridOpts.data = myDummyData;
}
};
//DOES NOT WORK BUT WHY
// $scope.$watch('filterOptions.filterText', function (newValue, oldValue) {
// if ($scope.filterOptions.filterText) {
// $scope.filteringText = newValue;
// $scope.updateData(newValue);
// }
// });
The idea is to have a navigation bar that contains a search field. Later I want to filter depending on rangesliders on further columns. However not even the standard string filtering works in my example.
Questions:
Could somebody tell me where my current problem is? More specifically: Why does the filtering from external input fields not work?
The other question is how can I bind min and max values of range sliders to e.g. the age column in my example? (directly related to the binding problem in question (1))
I looked around for answers, but either this is directly a problem of the binding that I cannot grasp, a mere programming js problem, or a ngGrid update to ui-grid problem.
Thanks a lot in advance
The answer to your first question, they have not really made a global search option for the UI-Grid yet, so you have to do a bit of a work around. The current way that the column filters work is angular watches the column filter input field for a change, and when you type in the box, it refreshes its filter. So your filter will not apply unless you force this input box to fire the change event.
The workaround is to simply filter the data and reload. For example:
In your HTML input search box, add a refresh
<input ng-model="searchText" ng-change="refreshData()" placeholder="Search...">
then in your app.js
$scope.refreshData = function() {
$scope.myGrid.data = $filter('filter')($scope.data, $scope.searchText);
};
oh, and don't forget to include $filter in your controller
app.controller('myController', function($scope, $filter) {}
I forked your example and modified it with this workaround. Check it out here:
http://plnkr.co/edit/Tr9cNm0lDy62dmF7LNlr?p=preview
try this:
$scope.gridOpts = {
data: myDummyData,
enableFiltering: true,
columnDefs: [
{name: 'Name', field: 'name', enableFiltering: true
, filter: {
noTerm: true,
condition: function(searchTerm, cellValue) {
return (cellValue+"" === $scope.filterOptions.filterText+"");
}
}
},
{name: 'Price', field: 'age'}
]
};
for input box: <input ng-model="searchText" ng-change="refresh()" placeholder="Search...">
$scope.refresh = function()
{
$scope.gridApi.core.refresh();
}
I hope it works...
There is a simple way to filter on ui-grid. In HTML
<input type="text" ng-model="searchText" ng-change="refreshData()" />
In your js file
app.controller('myController', function($scope, $filter) {
$scope.refreshData = function () {
$scope.myGrid.data = $filter('filter')($scope.myGridData, $scope.searchText);
}
$scope.myGrid = { ... }
$scope.dataBindingWithGrid = function () {
...
$scope.myGridData = data;
$scope.myGrid.data = data;
...
}
...
...
}

Categories

Resources