Using ng-repeat to generate select options (with Demo) - angularjs

controller:
$scope.send_index = function(event, val){
console.log(val);
$scope.variable = 'vm.areas['+val+'].name';
console.log( $scope.variable );
};
and this is in the view:
<select ng-model="vm.areas">
<option ng-repeat="area in vm.areas" ng-value="area" id="{{area}}" ng-click="send_index($event, $index)">{{area.name}}
</select>
<input value="{{variable}}">
where "vm" is my model.
Expression inside of an expression (Angular)
my problem is that i need to have an {{array[]}}, with the index as another expression,
e.g: {{Array[{{val}}]}}.
Already tryed this:
$scope.variable = ''+'vm.areas['+val+'].name'+'';
The problem is in the view, "variable" is shown like an string
(vm.areas[0].name)
and it donst get the valor of that query.

This is NOT the correct way to use ng-model with a <select> element in AngularJS:
<!-- ERRONEOUS
<select ng-model="vm.areas">
<option ng-repeat="area in vm.areas" ng-value="area" id="{{area}}" ng-click="send_index($event, $index)">{{area.name}}
</select>
<input value="{{variable}}">
-->
There is no need to use the ng-click directive. The select directive handles that automatically. The ng-model directive receives or sets the chosen option.
See:
Using ng-repeat to generate select options
Using select with ng-options and setting a default value
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
model: null,
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
]
};
}]);
<script src="https://unpkg.com/angular/angular.js"></script>
<div ng-app="ngrepeatSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
</form>
<hr>
<tt>model = {{data.model}}</tt><br/>
</div>

Try data-ng-value instead of value
<input data-ng-value="{{variable}}">

Related

how to bind .json file to auto complete drop down list in MVC AngularJS

I'm having large data of city names in .json file, i want to bind that all city names to my auto complete drop down list by using Mvc AngularJS so is there any way to do that,thanks in advance
https://github.com/ghiden/angucomplete-alt
You can make use of this plugin I think. Here's how you can use it.
<angucomplete-alt id="members"
placeholder="Search members"
pause="400"
selected-object="selectedCity"
remote-url="http://myserver.com/api/user/find?s="
remote-url-data-field="results"
title-field="name"
input-class="form-control form-control-small"/>
On server side you will receive the typed string as GET parameter.
Request.QueryString["type"];
Your server function should return the result in following JSON format.
{
results : [{'name': 'first city', 'name': 'second city'}]
}
2nd Option
In case you have to stick with static json file then you can use following approach as well. This will also work fast as all cities and loaded once and then filtering happens locally.
In Template
<div angucomplete-alt id="ex1"
placeholder="Search cities"
maxlength="50"
pause="100"
selected-object="selectedCity"
local-data="cities"
search-fields="name"
title-field="name"
minlength="1"
input-class="form-control form-control-small"
match-class="highlight">
</div>
then in your controller add this. This loads your json file into cities array which is used by the directive for auto complte purpose
$scope.cities = [];
$http.get('http://server/cities.json')..success(function(response) {
$scope.cities = response.data;
});
ng-options="color.Name for color in Colors"
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Colors = [{
Id: 1,
Name: 'Red'
}, {
Id: 2,
Name: 'Blue'
}, {
Id: 3,
Name: 'Green'
}];
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<select ng-model="ddlColors" ng-options="color.Name for color in Colors track by color.Id">
</select>
</div>
Controller code
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Fruits = [{
Id: 1,
Name: 'Apple'
}, {
Id: 2,
Name: 'Mango'
}, {
Id: 3,
Name: 'Orange'
}];
});
HTML Code
<label class="item item-input item-select">
<div class="input-label" style="color:#387ef5;">
Type of call :
</div>
<select name="fruitType" class="form-control" ng-change="getSectedTypeValue(selectedID)" ng-model="selectedID" ng-options=" fruitType as fruitType.Name for fruitType in Fruits track by fruitType.Id" value="{{fruitType.Id}}" required>
<option value=""> Select Call Type </option>
</select>
</label>

Angular - select - filter more than one values

I have a dropdown in Angular. And I want to restrict some values.
I tried with filter as in the below Plunkr.
It works for only one id at a time. But if I want to display two records for example 1 and 2. How to do it ?
Plunkr:
http://plnkr.co/edit/CumFFs9dMMb4krosKKZC?p=preview
Javascript
(function(angular) {
'use strict';
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.filterCriteria ;
$scope.data = {
repeatSelect: null,
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
],
};
}]);
})(window.angular);
HMTL
<body ng-app="ngrepeatSelect">
<div ng-controller="ExampleController">
<form name="myForm">
Filter <input type="text" ng-model="filterCriteria"> <br><br>
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
<option ng-repeat="option in data.availableOptions | filter : filterCriteria" value="{{option.id}}">{{option.name}}</option>
</select>
</form>
<hr>
<tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
</div>
</body>
Update:-
I am trying to achieve to reduce some of the available drop down values from the original big list to a small list. ( Side note : I just need a single select and not multi-select feature.)

Sprangular ng-change property in dropdown variant

i'm trying to change the sprangular variant selection(using button) to selecet option,
but i got stuck using angular directive to change selected value (i'm tried ng-change, ng-selected), i think my mistake in directives property,
this my wrong HTML code :
<select class="form-control select-styled"ng-change="selectValue(item.value)" ng-model="item.value">
<option ng-repeat="item in option.values">{{item.value.presentation}}</option></select>
i'm trying to use ng-click like this
<select class="form-control select-styled">
<option ng-repeat="item in option.values" ng-click="selectValue(item.value)">{{item.value.presentation}}</option>
but it's only working on Firefox, not on safari,chrome.
this is the variantSelection.coffe code
'use strict'
Sprangular.directive 'variantSelection', ->
restrict: 'E'
templateUrl: 'directives/variant_selection.html'
scope:
product: '='
variant: '='
class: '='
change: '&'
controller: ($scope) ->
$scope.values = {}
$scope.$watch 'variant', (newVariant, oldVariant)->
$scope.change({oldVariant: oldVariant, newVariant: newVariant}) if newVariant != oldVariant
$scope.isValueSelected = (value) ->
$scope.values[value.option_type_id]?.id == value.id
$scope.isValueAvailable = (value) ->
$scope.product.availableValues(_.values($scope.values))
$scope.selectValue = (value) ->
$scope.values[value.option_type_id] = value
$scope.variant = $scope.product.variantForValues(_.values($scope.values))
link: (scope, element, attrs) ->
scope.values = {}
if scope.variant
for value in scope.variant.option_values
scope.values[value.option_type_id] = value
In angular document you can see as like a example from the section Using ngRepeat to generate select options
HTML:
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" ng-change="selectValue(data.repeatSelect)" id="repeatSelect" ng-model="data.repeatSelect">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
</form>
<hr>
<tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
</div>
JS:
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
repeatSelect: null,
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
],
};
}]);
// Code goes here
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
repeatSelect: null,
availableOptions: [{
id: '1',
name: 'Option A'
}, {
id: '2',
name: 'Option B'
}, {
id: '3',
name: 'Option C'
}],
};
$scope.selectValue = function(value) {
console.log(value);
alert(value);
};
}]);
<!DOCTYPE html>
<html ng-app="ngrepeatSelect">
<head>
<script data-require="angular.js#1.4.7" data-semver="1.4.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect" ng-change="selectValue(data.repeatSelect)">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
</form>
<hr />
<tt>repeatSelect = {{data.repeatSelect}}</tt>
<br />
</div>
</body>
</html>
here is the link where they can try to solve this problem. Thanks.
This code working only firefox and IE
<option ng-click="this.$parent.selectValue(data.repeatSelect)" ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
(the problem in sprangular while change variant selection into a dropdown)
using an ng-model and ng-change...
and the problem is the json not an objct
like this code :
<select class="form-control select-styled" ng-model="item" ng-change="selectValue(item)">
<option ng-repeat="item in option.values" value="{{ item.value }}">{{item.value.presentation}}</option></select>
and editing the variantSelection.coffee
$scope.selectValue = (value) ->
obj = JSON.parse(value) //add this one into selectValue function
$scope.values[obj.option_type_id] = obj
$scope.variant = $scope.product.variantForValues(_.values($scope.values))
and selected select option will work in every browser..
hope this usefull for others who have the same problem with me..
sorry #RIPenglish
try this
<select class="form-control select-styled">
<option ng-repeat="item in option.values" ng-click="selectValue(item.value)">{{item.value.presentation}}</option>
ngRepeat is a directive.
So it has own $score.

Angularjs select value is undefined

Now I am trying to get the value from select dropdown, but it return undefined. The thing is in html level it works as expect, Here is my code:
<div class='subcontent'>
<input id="me" type="radio" class='choosemethod' ng-model="paymentmethod" value="Y"><label for="me" class='choosemethod'>Me</label>
<input id="company" type="radio" ng-model="paymentmethod" value="N" class='choosemethod'><label for="company" class='choosemethod'>My Company</label><br/>
<span class='helptext'>Who makes payments to this account?</span><span class='help' style='margin-left:20px;width:20px;height:20px;'>help</span>
</div>
<div class='paymentmethods subcontent' ng-switch on="paymentmethod">
<select ng-model='selectedmethod' ng-init="selectedmethod=Memethods[0]" id='methods' ng-switch-when='Y'>
<option ng-repeat="method in Memethods" value="{{method}}">{{method}}</option>
</select>
<select ng-model='selectedmethod' ng-init="selectedmethod=companies[0]" ng-switch-when='N' style='float:left'>
<option ng-repeat='companyoption in companies' value="{{companyoption}}">{{companyoption}}</option>
</select>
<div class='clear'></div>
<label for ='methods'>Payment Method</label><span class='help' style='margin-left:20px;width:20px;height:20px;'>help</span>
</div>
In js:
$scope.Memethods = ['Same as Card/Account Name','American Express','American Express Corp','Cash','Checking','MasterCard','My Visa','VISA'];
$scope.companies = ['Company Paid','MyAMEX'];
it shows fine in page, but when I try to get the value, it shows undefined. any idea?
This is the classic "angular dot notation" issue.
Here is a working example
Basically, ng-switch creates a new scope, so when the select sets the selectedmethod property, it is doing so on the new scope, not the controller scope as you are expecting. One solution is to create a parent object for your model.
angular.module('app',[])
.controller('main', function($scope){
$scope.selection = {};
$scope.Memethods = ['Same as Card/Account Name','American Express','American Express Corp','Cash','Checking','MasterCard','My Visa','VISA'];
$scope.companies = ['Company Paid','MyAMEX'];
})
and note how it's referenced differently in the html:
<select ng-model='selection.selectedmethod' ng-init="selection.selectedmethod=companies[0]" ng-switch-when='N' style='float:left'>
<option ng-repeat='companyoption in companies' value="{{companyoption}}">{{companyoption}}</option>
</select>
A different (maybe better) way would be to use the "ControllerAs" syntax, which has the effect of doing this for you.
angular.module('app',[])
.controller('main', function($scope){
this.Memethods = ['Same as Card/Account Name','American Express','American Express Corp','Cash','Checking','MasterCard','My Visa','VISA'];
this.companies = ['Company Paid','MyAMEX'];
})
<body ng-app="app" ng-controller="main as main">
<div class='subcontent'>
<input id="me" type="radio" class='choosemethod' ng-model="paymentmethod" value="Y">
<label for="me" class='choosemethod'>Me</label>
<input id="company" type="radio" ng-model="paymentmethod" value="N" class='choosemethod'>
<label for="company" class='choosemethod'>My Company</label>
<br/>
<span class='helptext'>Who makes payments to this account?</span><span class='help' style='margin-left:20px;width:20px;height:20px;'>help</span>
</div>
<div class='paymentmethods subcontent' ng-switch on="paymentmethod">
<select ng-model='main.selectedmethod' ng-init="main.selectedmethod=main.Memethods[0]" id='methods' ng-switch-when='Y'>
<option ng-repeat="method in main.Memethods" value="{{method}}">{{method}}</option>
</select>
<select ng-model='main.selectedmethod' ng-init="main.selectedmethod=main.companies[0]" ng-switch-when='N' style='float:left'>
<option ng-repeat='companyoption in main.companies' value="{{companyoption}}">{{companyoption}}</option>
</select>
<div class='clear'></div>
<label for='methods'>Payment Method</label><span class='help' style='margin-left:20px;width:20px;height:20px;'>help</span>
</div>
<div>{{main.selectedmethod}}</div>
</body>
you can refer to this simple example
html code :
<div ng-controller="Main" ng-app>
<div>selections = {{selections}}</div>
<div>
<p>Model doesn't get updated when selecting:</p>
<select ng-repeat="selection in selections" ng-model="selection" ng-options="i.id as i.name for i in items">
<option value=""></option>
</select>
</div>
js code:
function Main($scope) {
$scope.selections = ["", "id-2", ""];
$scope.reset = function() {
$scope.selections = ["", "", ""];
};
$scope.sample = function() {
$scope.selections = [ "id-1", "id-2", "id-3" ];
}
$scope.items = [{
id: 'id-1',
name: 'Name 1'},
{
id: 'id-2',
name: 'Name 2'},
{
id: 'id-3',
name: 'Name 3'}];
}
The ng-model inside value must have Initialize before it represents. So the ng-init comes before the ng-model. inside the options $first is used for select the first value.
<select ng-init= "selectedmethod=companies[0]" ng-model='selectedmethod' ng-switch-when='N' style='float:left'>
<option ng-repeat='companyoption in companies' value="{{companyoption}}" ng-selected="$first">{{companyoption}}
</option>
</select>

ng-select gives only string, but I want an integer

This is my angular html file code. In my mongo database frequencyType added as frequencyType = "1", but I want frequencyType = NumberInt(1);
<div class="span4">
<select class="span12 combobox" ng-model="frequencyType" required>
<option value="1">Daily</option>
<option value="2">Weekly</option>
<option value="3">Monthly</option>
<option value="4">Yearly</option>
</select>
</div>
I get in my database frequencyType = "1" but I want frequencyType = NumberInt(1).
There is an easier way:
Just use value*1 as your id, that will convert the string to int without changing the value... assuming the id is an integer.
so the result is>
<div ng-app ng-controller="MyCtrl">
<select ng-model="selectedItem" ng-options="selectedItem*1 as selectedItem for selectedItem in values"></select>
selectedItem: {{selectedItem}}
</div>
This will work in more cases, since indexOf is not available in objects, only in arrays. This solution works for objects with integers as keys (for example if some keys are missing, or if you use db ids)
Most solutions discussed here require using the ngOptions directive instead of using static <option> elements in the HTML code, as was the case in the OP's code.
Angular 1.6.x
Edit If you use Angular 1.6.x, just use the ng-value directive and it will work as expected.
angular.module('nonStringSelect', [])
.run(function($rootScope) {
$rootScope.model = { id: 2 };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<div ng-app="nonStringSelect">
<select ng-model="model.id">
<option ng-value="0">Zero</option>
<option ng-value="1">One</option>
<option ng-value="2">Two</option>
</select>
{{ model }}
</div>
Older versions
There is a way to make it work while still using static elements. It's shown in the AngularJS select directive documentation.
The idea is to use a directive to register a parser and a formatter on the model. The parser will do the string-to-int conversion when the item is selected, while the formatter will do the int-to-string conversion when the model changes.
Code below (taken directly from the AngularJS documentation page, credit not mine).
https://code.angularjs.org/1.4.6/docs/api/ng/directive/select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting
angular.module('nonStringSelect', [])
.run(function($rootScope) {
$rootScope.model = { id: 2 };
})
.directive('convertToNumber', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(val) {
return parseInt(val, 10);
});
ngModel.$formatters.push(function(val) {
return '' + val;
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="nonStringSelect">
<select ng-model="model.id" convert-to-number>
<option value="0">Zero</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
{{ model }}
</div>
I've just had the same problem and figured out the right way to do this - no 'magic' required. :)
function MyCtrl($scope) {
$scope.values = [
{name : "Daily", id : 1},
{name : "Weekly", id : 2},
{name : "Monthly", id : 3},
{name : "Yearly", id : 4}];
$scope.selectedItem = $scope.values[0].id;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
<select ng-model="selectedItem" ng-options="selectedItem.id as selectedItem.name for selectedItem in values"></select>
selectedItem: {{selectedItem}}
</div>
I think the angular way to do this is to use the directive "convert-to-number" in the select tag.
<select class="span12 combobox" ng-model="frequencyType" required convert-to-number>
<option value="1">Daily</option>
<option value="2">Weekly</option>
<option value="3">Monthly</option>
<option value="4">Yearly</option>
</select>
You can see the documentation and a fiddle here at the end of the page : https://docs.angularjs.org/api/ng/directive/select
I suggest you to try to use indexOf.
JS
function MyCtrl($scope) {
$scope.values = ["Daily","Weekly","Monthly","Yearly"];
$scope.selectedItem = 0;
}
HTML
<div ng-app ng-controller="MyCtrl">
<select ng-model="selectedItem" ng-options="values.indexOf(selectedItem) as selectedItem for selectedItem in values"></select>
selectedItem: {{selectedItem}}
</div>
Demo Fiddle
So send to mongoDB $scope.selectedItem value
This is the easiest way I have found so far:
function Controller($scope) {
$scope.options = {
"First option" : 1,
"Second option" : 2,
"Last option" : 10
}
$scope.myoption = 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Controller">
<select ng-model="myoption" ng-options="label for (label, value) in options"></select>
Option Selected: {{myoption}}
</div>
Or, if you want to use numeric indexes:
function Controller($scope) {
$scope.options = {
1 : "First option",
2 : "Second option",
10 : "Last option"
}
$scope.myoption = 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Controller">
<select ng-model="myoption" ng-options="value*1 as label for (value, label) in options"></select>
Option Selected: {{myoption}}
</div>
For Angular 2, follow the rabit...

Resources