I have a dropdown with a backing JSON like this:
$scope.tradestyles = [
{"id":"1","source":"Source One","name":"Name One"},
{"id":"2","source":"Source Two","name":"Name Two"}
]
This is the dropdown, using select2, the model is the ID of the selected tradestyle:
<select id="tradestyle" ui-select2 ng-model="currentTradestyle" >
<option ng-repeat="tradestyle in tradestyles" value="{{tradestyle.id}}">
{{tradestyle.name}}
</option>
</select>
Next to it, I want to place a text field where the selected tradestyle's name is shown and
can be edited.
<input type="text" ng-model="currentTradestyle" />
How do I change the model of the latter to point to the selected tradestyle's name rather than the ID? In other words, how do I traverse the scope object to point to the sibling name value of the selected ID value?
If i have understood your question correctly, you need to use ng-options for binding to a object rather than a field. So it becomes
<select id="tradestyle" ui-select2 ng-model="currentTradestyle" ng-options="style.name for style in tradestyles">
</select>
<input type="text" ng-model="currentTradestyle.id" />
<input type="text" ng-model="currentTradestyle.name" />
See my fiddle here
http://jsfiddle.net/cmyworld/UsfF6/
<div ng-app="myApp">
<div ng-controller='Ctrl'>
<select id="tradestyle" ng-model="currentTradestyle" update-model="tradestyles">
<option ng-repeat="style in tradestyles" value="{{style.id}}">{{style.name}}</option>
</select>
<input type="text" ng-model="currentTradestyle.name" />
</div>
</div>
JavaScript:
var app = angular.module('myApp', []);
app.controller('Ctrl', ['$scope', '$rootScope', function ($scope, $rootScope) {
$scope.tradestyles = [{
"id": "1",
"source": "Source One",
"name": "Name One"
}, {
"id": "2",
"source": "Source Two",
"name": "Name Two"
}];
}]);
app.directive('updateModel', function() {
return {
require: '?ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
function parser(value) {
if(value) {
return _.findWhere(scope[attrs.updateModel], {id: value});
}
}
modelCtrl.$parsers.push(parser);
},
}
});
This might satisfy the issues you raised in your comment. It uses tradestyle.id rather than $index in the <option>s which means the selected item works in cases where a filter is applied to the collection. The additional of a $parser ensures the tradestyle.id actually becomes the selected tradestyle item before being applied to the currentTradestyle model property.
Theres a dependency on Underscore but you can remove that with a more long hand alternative to the findWhere() method.
http://jsfiddle.net/asperry1/Zfecq/6/
I believe what you are looking for is something like this:
<div ng-app="myApp">
<div ng-controller='Ctrl'>
<select id="tradestyle" ui-select2 ng-model="currentTsIndex">
<option ng-repeat="tradestyle in tradestyles" value="{{$index}}">{{tradestyle.name}}</option>
</select>
<input type="text" ng-model="tradestyles[currentTsIndex].name" />
</div>
</div>
Working fiddle:
Related
This question already has answers here:
AngularJS: ng-model not binding to ng-checked for checkboxes
(7 answers)
Closed 3 years ago.
I am trying to use ng-repeat directive with track by expression, to show radio buttons, when I submit the value gets attached in the model and when I reopens the page using the values in model, the radio button does not show checked.
I have implemented same with plane string model + string values . But this time am trying with objects.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<form name="myForm">
<p>New TRY</p>
<ul>
<li ng-repeat="i in peopleNew.person">
<label>
{{i}}
<input type="radio" ng-model="peopleServer.person"
name="same" ng-value="i" />
</label>
</li>
</ul>
</form>
<div>
JS code
angular.module('app', [])
.controller('MyCtrl', ($scope) => {
$scope.peopleNew ={
person: {
"name": "Ringo",
"id": "R",
"subj": "Sci"
}
}
$scope.peopleServer= {
person: {"name":"Ringo"}
}
});
As per above, I should have 4 radio buttons on the screen, I am able to select 1 and submit. And then when I again open it in my model the person have the right value which was saved thorough ng-value but still on UI i don't see the radio button as checked for name Ringo should be checked. Model have:
$scope.peopleServer= {
person: {name:"Ringo"}
}
Tried Solutions
ng-checked expression , although I read that ng-model and ng-checked
should not be used together, ideally using model binding it should be chcked.
explanationI read about ,ng-repeat is not rendering properly so i tried to re render forcefully but did not work.
Removed ng-checked from the template still did not work.
Track by works for string values in ng-repeat.In ng-options it worked for object values also, but then its not input element but a select element
Someone help understand, when you reload or you already have the value in model,how the radio button be selected
angular.module('app', [])
.controller('MyCtrl', ($scope) => {
$scope.peopleNew ={
person: {
"name": "Ringo",
"id": "R",
"subj": "Sci"
}
}
//uncomment for testing.
$scope.peopleServer= {
person: {"name":"Ringo"}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<form name="myForm">
<p>New TRY</p>
<ul>
<li ng-repeat="i in peopleNew.person">
<label>
{{i}}
<input type="radio" ng-model="peopleServer.person"
name="same" ng-value="i" />
</label>
</li>
</ul>
</form>
<div>
automatically ? all my tries above are not working am i missing something.
You have some syntax errors, missing model values and some unnecessary markup. First, you can get rid of the ng-checked altogether. That will be handled automatically if you set your ng-model and ng-value properly. Since your objects are unique there's no need for track by.
When using AngularJS directives (such as ng-value) you do not need to use braces to reference your model values. So ng-value="{{person}}" becomes ng-value="person".
You refer to myObj.person, but there doesn't appear to be a corresponding model value. Below is an edit of the code and markup you have provided showing that it really does work to use an object as the value for your radio buttons.
angular.module('app', [])
.controller('MyCtrl', ($scope) => {
$scope.people = [{
name: "John",
id: "J"
}, {
name: "Paul",
id: "P"
}, {
name: "George",
id: "G"
}, {
name: "Ringo",
id: "R"
}];
$scope.myObj = {
person: $scope.people[1]
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<form name="myForm">
<p>Decisions</p>
<ul>
<li ng-repeat="person in people">
<label>
{{ person.name }}
<input type="radio" ng-model="myObj.person"
name="sameName" ng-value="person" />
</label>
</li>
</ul>
</form>
<div>
{{ myObj.person }}
</div>
</div>
I seem to have trouble setting a default value for a select dropdown with AngularJS. I have read similiar topics on StackOverflow, but none of the proposed solutions worked for me, so I decided to finally ask you guys :)
Bascically I want to implement an entry editing functionality in my app. So, the user clicks on the edit button, a modal pops up with a form with values filled from the object that was passed to the modal controller. I mean all of the values, but the "category" which I want to be presented as a dropdown select.
I think it's going to be easier to show in code, so I prepared this fiddle:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.dataReceived = {
category: "FOOD"
}
$scope.availableCategories = {
FOOD: "Food and drinks",
FREE_TIME: "Free time",
HOUSING: "Housing costs"
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="form-group">
<label for="select-category">Select category:</label>
<select class="form-control" id="select-category" ng-model="dataReceived.category" required>
<option ng-repeat="(key,value) in availableCategories" ng-value="key">
{{value}}
</option>
</select>
</div>
</div>
I tried different ways of fixing it, but none have worked so far so please help! All I want to do is for the dropdown to say "Food and drinks" by default if passed object's category is "FOOD".
Cheers!
I think you should try to use ng-options with key value pairs instead.
Like this:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.dataReceived = {
category: "FOOD"
}
$scope.availableCategories = {
FOOD: "Food and drinks",
FREE_TIME: "Free time",
HOUSING: "Housing costs"
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="form-group">
<label for="select-category">Select category:</label>
<select class="form-control" id="select-category" ng-model="dataReceived.category" ng-options="key as value for (key , value) in availableCategories " required>
</select>
</div>
</div>
Hope it helps.
I'm using UI-Bootstrap so I can use them both Angular and bootstrap. I want to access the value from a select tag that the "controllerCountries" controller have and use that value as a parameter to the fill the select "selectedServices". I want to do that because the logic of the program will be that when I choose a country of a list of countries in a select tag, use that value to fill the another select tag.
My HTML is here:
<div style="margin-top: 15px" class="col-md-6">
<div id="form-pais"class="form-group">
<label class=" control-label">Country:</label>
<div class="selectContainer">
<select ng-controller="controllerCountries" class="form-control" id="abvCountry" name="abvCountry" ng-model="countrySelected">
<option value="gt">Guatemala</option>
<option value="sl">El Salvador</option>
<option value="hn">Honduras</option>
</select>
</div>
</div>
</div>
<div style="margin-top: 15px" class="col-md-6">
<div class="form-group">
<label class=" control-label">Services:</label>
<div ng-controller="controllerServices" class="selectContainer">
<select class="form-control" id="selectServices"ng-model="servicios" ng-options="y for (x, y) in serviciosgt" text="">
</select>
</div>
My JS file looks like that:
//Heres the list of services in the objects. I use this to fill the second select.
app.controller('controllerServices', function($scope)
{
$scope.serviciosgt =
{
consMiami : "Consolidación Miami",
contCompletosGT: "Contenedores Completos",
cargMartConsolidadGT : "Carga Maritima Consolidada",
cargAereaRegularGT: "Carga Áerea Regular"
};
$scope.serviciosSL =
{
contCompletosSl : "Contenedores Completos",
cargMartConsolidadSl: "Carga Marítima Consolidada",
cargAereaRegularSl: "Carga Áerea Regular"
};
$scope.serviciosHN =
{
contCompletosHN : "Contenedores Completos",
cargMartConsolidadHN: "Carga Marítima Consolidada",
cargAereaRegularHN: "Carga Áerea Regular"
};
});
//Heres the controller to fill.
app.controller('controllerCountries', function($scope)
{
$scope.countrySelected ='';
$scope.$watch('countrySelected', function () {
if($scope.countrySelected=="gt")
{
console.log("Select GT");
}
else if($scope.countrySelected=="sl")
{
console.log("Select SL");
}
else if($scope.countrySelected=="hn")
{
console.log("Select HN");
}
});
});
Right now I can access the value of the first "controllerCountries" and log that value on the console, but thats it. And, as you can see, I fill the select with the first object, but I wan them to be dinamic. Can anyone help me please. And if you look that my code is wrong, youre welcome to fix it.
Greetings and thanks.
HTML view
First of all, you don't need that $watch, you can use ng-change to fire a callback when the select value (ng-model) is changed. you can write your if statements there.
Second, don't use ng-controller on a select, you have ng-options to dynamically place nested <option> elements inside the <select>.
Lastly, if you want to fill select number 2 using a value you've selected from select number 1, just reference the correct data when the ngChange callback is fired
$scope.onCountryChange = function (country) {
if(country=="gt")
{
console.log("Select GT");
$scope.serviciosgt = { ... };
}
else if(country=="sl")
{
console.log("Select SL");
$scope.serviciosgt = { ... };
}
else if(country=="hn")
{
console.log("Select HN");
$scope.serviciosgt = { ... };
}
};
your select could look something like this
<select class="form-control"
name="abvCountry"
ng-change="onCountryChange(countrySelected)"
ng-options="country for country in countries" ng-model="countrySelected">
</select>
While
$scope.countries = ["gt", "sl", "hn"];
I have a <select> in my application, which is supplied data from an ng-repeat but each option in the select has data of it's own. Simply enough, here is the JSON payload I am working with:
{
"0":{
"name":"Mover",
"scalar":[
{
"name":"Size",
"unit":"m"
},
{
"name":"Speed",
"unit":"m/s"
}
]
},
"1":{
"name":"Stationary",
"scalar":[
{
"name":"Size",
"unit":"m"
}
]
},
"2":{
"name":"Vibrator",
"scalar": [
{
"name":"Frequency",
"unit":"hz"
}
]
}
}
I need the outer 3 names in the select, but I'd like the 'scalar' values to show up as checkboxes next to the select. It's obviously got to be dynamic, so i was curious if there was a way to do this based off of the ng-repeat of the select. Another reason why I am asking is because due to formatting, I'd like to place the checkboxes outside of the ng-repeat (clearly since that's in a select) so not too sure how the checkboxes would access the repeat value. Below is the html snippet:
<div id="type-selection"
class="row ng-hide"
ng-show="rcw.page ==='Type Selection'">
<div class="col-md-6">
<div class="form-group">
<label for="rule-type">Type</label>
<select id="rule-type"
class="form-control"
ng-model="rcw.selectedRuleType">
<option ng-repeat="type in rcw.QueryTypes">{{type.name}}</option>
</select>
</div>
</div>
<div class="col-md-2" ng-repeat="ideally scalar in type from above^">
<label>
<input type="checkbox"
class="faChkSqr"
ng-model="ideally this would be dynamically tied to scalar.name </input>
<span></span>
<b>{{ideally this would be scalar.name}}</b>
</label>
</div>
</div>
Just not too sure if this is possible, or if I need to handle what's selected then from there in the javascript decide what needs to be displayed? Thanks in advance!
You are storing the selection in a variable: rcw.selectedRuleType
<select id="rule-type" class="form-control" ng-model="rcw.selectedRuleType">
<option ng-repeat="type in rcw.QueryTypes">{{type.name}}</option>
</select>
I guess you just have to loop over this object with your ng-repeat:
<div class="col-md-2" ng-repeat="scalar in rcw.selectedRuleType">
{{scalar.name}}
</div>
As a side note, I suggest you to use ng-options in your select:
<select ng-model="rcw.selectedRuleType"
ng-options="type as type.name in rcw.QueryTypes">
</select>
Try like this.
<li ng-repeat="n in items">{{n.name}}{{n.scalar}}
<select ng-model="selectme" ng-options="options.name for options in n.scalar">
<option value="">-- choose color --</option>
</select>{{selectme}}
</li>
We can create checkboxes based on the selection,But not sure how we can dynamically bind model based on scaler.name.
We need to set the value of option as scaler of selected option.Then we should listen to change event on select field & extract the scalar value from the selected value.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.QueryTypes = [{
"name":"Mover",
"scalar":[
{
"name":"Size",
"unit":"m"
},
{
"name":"Speed",
"unit":"m/s"
}
]
},
{
"name":"Stationary",
"scalar":[
{
"name":"Size",
"unit":"m"
}
]
},
{
"name":"Vibrator",
"scalar": [
{
"name":"Frequency",
"unit":"hz"
}
]
}
];
$scope.getScalarTypes=function(){
$scope.scalarTypes=JSON.parse($scope.selectedRuleType);
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div id="type-selection">
<div class="col-md-6">
<div class="form-group">
<label for="rule-type">Type</label>
<select id="rule-type"
class="form-control"
ng-model="selectedRuleType" ng-change="getScalarTypes()">
<option ng-repeat="type in QueryTypes" value="{{type.scalar}}">{{type.name}}</option>
</select>
</div>
</div>
<div class="col-md-2" ng-repeat="scalar in scalarTypes">
<label>
<input type="checkbox"
class="faChkSqr"</input>
<span></span>
<b>{{scalar.name}}</b>
</label>
</div>
</div>
</div>
</body>
</html>
I have a requirements, in which I have to show a combo-box (select). The options in it aren't fixed, I need to give a link to add more options, on whose click a text box must be shown within the select element, user will enter a value and it will be added in select's options. Please tell me how this can be achieved using Angular. jQuery provides a way to do that, but if i use that I am not able to bind the elements with Angular.
Regards
Nitin
Javascript file:
function ctrl($scope){
$scope.rows = ['Paul','John','Lucie'];
$scope.addRow = function(){
$scope.rows.push($scope.addName);
$scope.addName = "";
};
}
HTML page:
<body ng-controller="ctrl">
<select>
<option ng-repeat="row in rows" value="{{ row }}">{{ row }}</option>
</select>
<span class="input-append">
<input id="add" type="text" placeholder="Another one ?" ng-model="addName" />
<input type="submit" class="btn btn-primary" ng-click="addRow()" value="+ add" />
</span>
</body>
See: http://codepen.io/anon/pen/JdqqXj
I'd suggest that you take a look at the docs dedicated to the select control in AngularJS. In a nutshell, you can use the ngRepeat to generate the options for you. If you need to get them from a backend, you can use resolve in your routing options and a service to grab them for you.
The example by AngularJs's website:
HTML
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="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>
APP.JS
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
singleSelect: null,
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
],
};
}]);
You can also use ng-options, which is more recommended.
In regards to the textbox element, associate the two elements with ng-model.
Example: