AngularJS ng-repeat with radio inputs - angularjs

I have a list of options as an enum:
var Options = {
Option0: 0,
Option1: 1,
Option2: 2,
Option3: 3,
Option4: 4
};
And a sub-list of available options:
var availabledOptions = [
Options.Option0,
Options.Option2,
Options.Option4
];
I then try to show the list of available options as radio inputs but it doesn't work and I'm wondering why. $scope.selectedOption is not updated.
function main($scope) {
$scope.availabledOptions = availabledOptions;
$scope.selectedOption = Options.Option2;
}
</script>
<div ng-app ng-controller="main">
<ul>
<li ng-repeat="option in availabledOptions">
<input name="options" type="radio" ng-model="selectedOption" ng-value="option">option #{{option}}
</li>
</ul>
selected option: option #{{selectedOption}}
</div>
http://jsfiddle.net/1xgsqL67/
I tried ng-repeat="option in availabledOptions track by $index" and also without the name attribute, but it still doesn't work.
Thanks in advance!

Try the following:
ng-model="$parent.selectedOption"
My understanding is that ng-repeat creates it's own scope, and you have to go up one level.

Related

AngularJS ng-options ng-model option selected by id

Why this code doesn't work as expected? I expect China be selected in the select but it is empty.
<div ng-app="app">
<div ng-controller="appController" class="p-2" ng-init="init()">
<select
name="user_country"
class="form-control"
ng-model="country"
ng-options="item.id as item.title for item in countries track by item.id">
<option value="" disabled>Select Country</option>
</select>
</div>
</div>
Controller:
var app = angular.module('app', []).controller('appController', ['$scope', function($scope){
$scope.country = 3
$scope.countries = [
{id: 1, title: 'US'},
{id: 2, title: 'Japan'},
{id: 3, title: 'China'},
{id: 4, title: 'Russia'}
]
}])
I expect to see China rather than an empty field. Here is a CodePen example https://codepen.io/grinev/pen/YJERvz.
Udpated the ng-options to
ng-options="item.id as item.title for item in countries">
Answer
without track By - JSFiddle
with track By - JSFiddle
track by just helps Angular internally with array sorting as far as I know. The value of the options is defined by the first argument (in your case item). If you want it to be by id then you should use item.id as item.name for item in items
You need to be storing the object, not the id. So instead of $scope.country = 3; you need to put it after the countries array and set it to $scope.country = $scope.countries[2];

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/

Selecting an option by default

I am struggling with the following piece of code.
<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>
</body>
and in js
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 3, name: 'blah' }];
$scope.selectedItem = { id: 3, name: 'blah' };
});
I have a selected item by default. But it doesn't show up in the selection while the page loads.
I have provided my code in the following link
http://plnkr.co/edit/FlESsL?p=preview
In the given example the dropdown should by default select the item blah.
TIA
Mobin
The first thing you need to do is update your angularjs version, then you can simply follow the angular select examples.
In the provided link they use track by to display the correct object, I took the liberty of editing their example plunker and added your code Here it is!
as you can see, the only thing I added to your code was track by item.id
Try this:
<select id="s1" ng-model="selectedItem" ng-options="item.id as item.name for item in items"></select>
and:
$scope.selectedItem = 3;
Before putting question did you go through - https://docs.angularjs.org/api/ng/directive/ngOptions
Just make below change in your controller -
$scope.selectedItem = $scope.items[0];

Nested checkboxes in AngularJS resource with external options

I have this data structure, search:
{
id: '1',
name: 'Foo'
service_ids:
[
3,
8,
12
]
}
I then have another data structure, services, that matches the ids from service_ids above with the below:
[
{
id: 3,
name: 'Fighter'
},
{
id: 4,
name: 'Typhoon'
},
{
id: 8,
name: 'Kung'
},
{
id: 12,
name: 'Builder'
}
]
I want to display this in a form using AngularJS. The name is fine. I want to display all possible services as checkboxes and if the search has one of the services checked then it is ticked in the checkbox. Something like:
<li ng-repeat="search in searches">
<input ng-model="search.name">
<ul>
<li ng-repeat="service in services">
<input type="checkbox">
{{service.name}}
</li>
</ul>
</li>
I don't know how to link that checkbox to the service_ids and the services. Any help appreciated.
I am using $resource.
Update
Ignore my answer, misread you nesting request.
If anyone needs nesting guidance see below:
The best way to nest in angular that I have found is to create a template which is aware of child items like this:
<script type="text/ng-template" id="tree_item_renderer.html">
<span>{{tag.Name}}</span>
<ul ng-show="tag.Children.length > 0">
<li ng-repeat="tag in tag.Children" ng-include="'tree_item_renderer.html'" ></li>
</ul>
</script>
<ul class="tag-list">
<li ng-repeat="tag in tags" ng-include="'tree_item_renderer.html'" ></li>
</ul>
If I understand your question it should be as easy as:
<input type="checkbox" ng-model="search.service_ids[service.id]">
And you should also get bi-directional binding.
Updated
Just realized search.service_ids is an array not a map. So the solution above is not accurate.
You might want instead to use a filter:
<input type="checkbox" ng-checked="search.service_ids | contains:service.id">
Then
filter('contains', function() {
return function(haystack, needle) {
return haystack.indexOf(needle) >= 0;
}
});

AngularJS: need to attach a selected collection to a model

I'm building a CRUD and I want to some model to be linked to others. So on some update/create template I need to add some other model and save their id when submitting the form.
So I did a basic form that is served by my backend. Here is the part where I try to display the linked model:
<div ng-repeat="item in otherItems">
<select ng-model="item" name="item" >
<option value="1" ng-selected="item">
<option value="2" ng-selected="item">
<option value="3" ng-selected="item">
</select>
<a class="remove" ng-click="removeRelated(item)">remove</a>
</div>
<a ng-click="addRelated()"><i class="icon-plus"></i></a>
Note: otherItems could be empty at the beginning (when doing a create or when an item is not linked to any other related model's item).
So when one press add/remove it will trigger a controller's function:
$scope.addRelated = function (){
if (typeof $scope[otherItems]=="undefined")
$scope[otherItems] = new Array();
$scope[otherItems].push($scope[otherItems].length);
};
$scope.removeRelated = function (item){
console.debug(item);
var idx = $scope[otherItems].indexOf(item);
if (idx !== -1) {
$scope[otherItems].splice(idx, 1);
}
};
My problem is when I save I get the position of item in items (so it's always 0, 1, 2...) I won't have an array of selected ID.
I guess there is something wrong with my addRelated maybe. What am I doing wrong?
Here is a screenshot to understand the idea since I may not be very clear:
So something like this? http://plnkr.co/edit/6eqWL5
The markup..
<body ng-controller="MainCtrl">
<div ng-repeat="otherItem in otherItems">
<select ng-model="otherItem.selectedItem" ng-options="item for item in otherItem.items"></select>
<a ng-click="removeOtherItem($index)">remove</a>
</div>
<a ng-click="addOtherItem()">add</a>
<hr/>
Selected:
<ul>
<li ng-repeat="otherItem in otherItems">
otherItem[{{$index}}].selectedItem = {{otherItem.selectedItem}}
</li>
</ul>
</body>
The code
app.controller('MainCtrl', function($scope) {
$scope.otherItems = [
{
selectedItem: null,
items: [1, 2, 3]
},
{
selectedItem: null,
items: [4, 5, 6]
}
];
$scope.addOtherItem = function(){
$scope.otherItems.push({ items: [7, 8, 9]});
};
$scope.removeOtherItem = function(index) {
$scope.otherItems.splice(index, 1);
};
});
Sorry if it's off from what you're asking for... the question was a little vague, so I'm guessing at some of the functionality.

Resources