AngularJs Select Not Updating When Model Updated - angularjs

I'm trying to programmatically update the selected item from my controller and it's not working. When I click the submit button, all it does is clear out the select. What I expect is that the second option (Perth) gets selected.
Look at this plunker for more info. http://jsfiddle.net/ky5F4/
Thanks
<div ng-controller="MyController" ng-app>
<div>Number of datasets= {{datasets.length}}</div>
<div>
<select class="dataset" size="1" ng-model="selectedDataset">
<option ng:repeat="dataset in datasets" value="{{dataset.name}}">
<h3>{{dataset.name}}</h3>
</option>
</div>
<input type="button" value="submit" ng-click="Select()"></input>
</div>
function MyController($scope) {
$scope.datasets = [{
id: 'id-1',
name: 'Brisbane'
}, {
id: 'id-2',
name: 'Perth'
}, {
id: 'id-3',
name: 'Melbourne'
}];
$scope.selectedDataset = 'id-1';
$scope.Select = function () {
alert('testing');
$scope.selectedDataset = 'id-2';
}
}

Use ng-options instead of ng-repeat.
<select class="dataset" size="1" ng-model="selectedDataset"
ng-options="dataset.id as dataset.name for dataset in datasets">
Working fiddle
You can see the docs here

Related

How to show default option in select option (drop down box) in an ng-repeat of rows?

I have a list of names and activities displayed with ng-repeat which shows tabular data (shortened for brevity). The list box populates and I can show which SchoolDayID was previously stored and the value for this updates if you change the selection in the drop-down. When the form loads it does not select any value in the drop-down list. For the ng-select I have tried several variations, none of which worked. I am several days into this and have no idea what I am doing wrong or failing to understand. How do I get each drop down per row to select the correct item?
I have tried:
<select ng-model="selectedSchoolDayID" ng-init="selectedSchoolDayID = a.SchoolDayID" ng-options="x.ID as x.code for x in AMListData" >
</select>
and even:
<select class="form-group">
<option id="selectedSchoolDay" name="selectedSchoolDay" value="{{AMListData[0].ID}}" selected="{{AMListData[0].ID}} == {{a.SchoolDayID}}">{{AMListData[0].code}}</option>
<option id="selectedSchoolDay" name="selectedSchoolDay" value="{{AMListData[1].ID}}" selected="{{AMListData[1].ID}} == {{a.SchoolDayID}}">{{AMListData[1].code}}</option>
<option id="selectedSchoolDay" name="selectedSchoolDay" value="{{AMListData[2].ID}}" selected="{{AMListData[2].ID}} == {{a.SchoolDayID}}">{{AMListData[2].code}}</option>
</select>
Data for list box:
$scope.AMListData = participationSvc.amlist();
// from participationSvc:
'amlist': function listSelectionsController($scope) {
return [
{ ID: '0', code: 'PM Programming' },
{ ID: '1', code: 'AM Programming' },
{ ID: '2', code: 'Supplemental' }
];
},
HTML/AngularJS part:
<div ng-repeat="a in selectedAttendees | orderBy : a.LastName">
<!-- there could be many rows, once per name of person. each row should have a drop-down of its own -->
<div class="row">
<div>{{a.LastName}}</div>
...
<select class="col-md-5" id="SchoolDay" name="SchoolDay" ng-model="a.SchoolDayID">
<option data-ng-repeat="x in AMListData" name="SchoolDay" value={{x.ID}} ng-selected="{{(x.ID == selectedSchoolDay) ? true: false}}" >{{x.code}}</option>
</select>
<!-- Show me current selection and drop-down list data -->
<b> Selected ID: {{a.SchoolDayID}}</b>
<br />
<ul>
<li ng-repeat="x in AMListData">{{x.ID}} {{x.code}}</li>
</ul>
</div>
</div>
You can use default value in controller
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedSchoolDayID" ng-options="x.ID as x.code for x in AMListData" >
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a={
//SchoolDayID:'2'
};
$scope.selectedSchoolDayID=$scope.a.SchoolDayID || '1';//'1' is Default Value
$scope.AMListData=[
{ ID: '0', code: 'PM Programming' },
{ ID: '1', code: 'AM Programming' },
{ ID: '2', code: 'Supplemental' }
];
});
</script>
</body>
</html>

Angular setting default radio selection in ng-repeat

I am presenting a simple yes/no answer question to my users and I want to have a default radio button selected. The problem is that I could have any number of these questions presented to the user.
This is my code:
<div ng-form ng-repeat="i in offers track by $index" name="messageForm[$index]">
<div data-ng-repeat="option in closeListingOptions" class="radio">
<label>
<input type="radio" name="close" ng-model="i.close" value="{{option.id}}" ng-checked="option.checked" />{{option.name}}</strong>
</label>
</div>
</div>
My options are set as follows:
$scope.closeListingOptions = [
{
id: "1",
name: "Yes please",
checked: true
},
{
id: "0",
name: "No thanks",
checked: false
}
];
The above example works and check/sets "yes" as the default answer. However unless I manually select an option via a mouse click the value is not binding to the model.
I have read that ng-select should not be used with ng-options but i am not sure how else I can achieve this goal? It seems that I need something like:
i.close = "1":
But how can I set this for an unknown quntity since I don't know how many question will be presented?
1- Instead of value={{something}} you can use ng-value directive.
2- Each input pack should have its specific name.
Here is a working example:
var app = angular.module("app", []);
app.controller("MainCtrl", function($scope) {
$scope.offers = [{
number: 1
},
{
number: 2
}
];
$scope.closeListingOptions = [{
id: "1",
name: "Yes please",
checked: true
},
{
id: "0",
name: "No thanks",
checked: false
}
];
});
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-form ng-repeat="i in offers" name="messageForm[$index]">
<div data-ng-repeat="option in closeListingOptions" class="radio">
<label>
<input type="radio" name="close-{{i.number}}" ng-model="i.close" ng-value="option.id" ng-checked="option.checked" />{{option.name}}</strong>
</label>
</div>
{{i}}
<hr>
</div>
</body>
</html>
You should try this:
<input type="radio" name="close"
ng-model="option.checked" value="{{option.id}}"
ng-checked="option.checked" />{{option.name}}</strong>
This ng-model will updated the checked key of your data array and then you can fetch all the radio button selection as per their ids from that single variable.
Hope this helps.
I was able t achieve my goal with the following:
<div data-ng-repeat="option in closeListingOptions" class="radio" ng-init="i.closeListing = 1">
<label>
<input type="radio" name="close-{{i.id}}" ng-model="i.closeListing" ng-value="{{option.id}}" />
<strong>{{option.name}}</strong>
</label>
</div>
The solution was to use ng-init

Angularjs: Select ng-model not working

I'm having an issue with a selection box. When I select the option I can't get the value that I just selected. I read a lot of answers, but none of them seems to work for me. Here is my code.
HTML:
<select class="wide" style="width: 96%;height: 100px;"
ng-options="element as element.type for element in elements"
ng-model="selectedType" >
<option value="">Choose an option</option>
</select>
<p> {{selectedType}} </p>
Controller:
elements:[
{
desc: "example1",
article: "OF",
type: "example1Type"
},
{
desc: "example2",
article: "P-8955625",
type: "example2Type"
}
];
$scope.selectedType = "";
The <p> {{selectedType}} </p> shows nothing.
Thanks in advance
The as its only for the display value, but for the ng-model present the entire selected item.
so you need wirte:
<p> {{selectedType.type}} </p>
https://embed.plnkr.co/bicmN1loBGdcxsWOLv6x/
elements needs to be set in the controller scope. e.g.
app.controller('ExCtrl', function($scope) {
$scope.elements = [{
desc: "example1",
article: "OF",
type: "example1Type"
}, {
desc: "example2",
article: "P-8955625",
type: "example2Type"
}];
});
Also, attach the controller to your view. e.g.
<body ng-controller="ExCtrl">
<select class="wide"
ng-options="element.type for element in elements"
ng-model="selectedType" >
<option value="">Choose an option</option>
</select>
<p>{{selectedType}} </p>
</body>
Et voila!
See the repl

angularjs dynamic add option field with disable previous selected option

Hi I am adding Dynamically form fields like this
<div ng-repeat="exam_student in exam_students">
<select
ng-model="exam_student.student_id"
options="students"
ng-options="student.id as student.name for student in students">
</select>
<button type="button" ng-click="removeStudent($index)">-</button>
</div>
<button type="button" ng-click="addStudent()">Add Student</button>
js
$scope.students = [{id: 1, name: 'st1'},
{id: 2, name: 'st2'}];
$scope.exam_students = [{}];
$scope.addStudent = function(){
$scope.exam_students.push({});
}
$scope.removeStudent = function(index){
$scope.exam_students.splice(index,1);
}
Each time a user clicks on Add Student button the form field added but how do i disable the previous selected option in a select element.
Thank you for your any help and suggestions
didn't fully test or optimize it, but this is something you can do.
add track by $index in ng-repeat and add ng-disabled in the select tag with
<div ng-controller='MyController'>
<div ng-repeat="exam_student in exam_students track by $index">
<select
ng-model="exam_student.student_id"
options="students"
ng-options="student.id as student.name for student in students"
ng-disabled="exam_students.length > 1 && exam_students.length > $index + 1">
</select>
<button type="button" ng-click="removeStudent($index)">-</button>
</div>
<button type="button" ng-click="addStudent()">Add Student</button>
</div>
https://jsfiddle.net/4xfzmuub/
exam_students.length > 1 is to prevent the first field from being disabled
===========================================================================
updated answer. Instead of using select with ng-options, I chose to use select with ng-repeat option. This was what I tried and not working.
ng-options="student.id as student.name disable when student.disable for student in students"
The options were able to be disabled. Unfortunately Angular won't let me set the value to ng-model since the option has been disabled. A workaround is to use select with ng-repeat option
html:
<div ng-controller='MyController'>
<div ng-repeat="exam_student in exam_students track by $index">
<select ng-model="exam_student.student_id" ng-change="hasChange()">
<option ng-repeat="student in students" value={{::student.id}} ng-disabled="student.disable">{{::student.name}}</option>
</select>
<button type="button" ng-click="removeStudent($index)">-</button>
</div>
<button type="button" ng-click="addStudent()">Add Student</button>
</div>
js:
var app = angular.module('myApp', []);
app.controller('MyController', ['$scope', MyController]);
function MyController($scope) {
// I suggest adding an empty object so that we can re-select the options
$scope.students = [{},{id: 1, name: 'st1', disable: false},
{id: 2, name: 'st2', disable: false},
{id: 3, name: 'st3', disable: false}];
$scope.exam_students = [{}];
$scope.addStudent = function(){
$scope.exam_students.push({});
}
$scope.removeStudent = function(index){
$scope.exam_students.splice(index,1);
$scope.hasChange();
}
$scope.hasChange = function() {
// using a lookup table, instead of 2 nested loops, for a better performance when the list gets large
var lookupTable = {};
// store the student_id in the lookupTable and set it to true
// worth noting since I am using option tag, student_id will be stored as string instead of number, but it is ok because key in javascript object will be converted to string
$scope.exam_students.forEach(function(exam_student) {
lookupTable[exam_student.student_id] = true;
// or lookupTable[Number(exam_student.student_id)] = true;
});
// loop through the options and if student_id is true/there, set disable accordingly
$scope.students.forEach(function(student) {
if(lookupTable[student.id]) {
student.disable = true;
}else {
student.disable = false;
}
//or student.disable = lookupTable[student.id];
});
}
}
https://jsfiddle.net/apop98jt/

Angular: how to get a template ng-model into a directive for filtering

I'm trying to create a directive which displays the template below and will ultimately allow for easy filtering. When an option on the select list is selected and a value entered into the input box the model will change. I need the directive to contain this model and then use the model for filtering.
This is as far as I've got so far. Can anyone give me some guidance on this as I'm pretty sure there's redundant code in my example too.
<div ng-controller="resultsCtrl">
<div ng-controller="searchFilterCtrl">
<dynamic-filters dynamic-filters-directive-search="getSearchFilters"></dynamic-filters>
</div>
<div ng-repeat="person in persons | filter: search">
{{person.name}}
</div>
template:
<select ng-model="filterType">
<option value="age">Age</option>
<option value="customerId">CustomerID</option>
<option value="productId">ProductID</option>
</select>
<input type="text" name="select-option-value" ng-model="search[filterType]">
<p>You want to filter the field : {{filterType}}</p>
I think you are close but it's actually simpler. Try this
index HTML:
<div ng-controller="resultsCtrl">
<dynamic-filters search="search"></dynamic-filters>
<div ng-repeat="person in persons | filter: search">
{{person.name}}
</div>
</div>
directive HTML:
<select ng-model="filterType">
<option value="age">Age</option>
<option value="customerId">CustomerID</option>
<option value="productId">ProductID</option>
<option value="name">Name</option>
</select>
<input type="text" name="select-option-value" ng-model="search[filterType]">
<p>You want to filter the field : {{filterType}}</p>
script.js JS code:
angular.module('app', ['dynamicFiltersDirective']).controller('resultsCtrl', function($scope){
$scope.persons = [{
name: 'Jim',
age: 18,
customerId: 1,
productId: 4
},{
name: 'Frank',
age: 20,
customerId: 2,
productId: 5
},{
name: 'Bob',
age: 20,
customerId: 3,
productId: 5
}];
});
directive JS code:
angular.module('dynamicFiltersDirective', [])
.directive('dynamicFilters', function() {
return {
restrict: 'AE',
scope: {
search: '='
},
link: function(scope) {
scope.$watch('filterType', function(v) {
if(!v) {return;}
//clear out the search
scope.search = {};
scope.search[v] = '';
});
},
templateUrl: 'filtertemplate.html'
}
});

Resources