Update: Solved! Please see my answer below.
I am trying to display a different image with each select option in Angular. As a user clicks on each option in a menu, a different image appears next to the menu. All of this is before the form is submitted. Basically trying to do what is done here in this fiddle, but in Angular: http://jsfiddle.net/treyh/xf2pq/
html:
Current image: {{myCar.url}}
<br>
<select ng-model="myCar" class="form-control">
<option value="">Choose a car...</option>
<option ng-repeat="car in cars" value="{{car}}" data-image = "{{car.url}}">{{car.label}}</option>
</select>
in the js file, inside the controller:
$scope.cars = [
{url: 'Volvo.png', label: 'Volvo'},
{url: 'Benz.png', label: 'Benz'},
{url: 'JohnDeer.png', label: 'John Deer'},
{url: 'BMW.png', label: 'BMW'},
];
I have figured out how to do this using ng-repeat and $Scope.
in the js file, inside the controller:
$scope.cars = ['Volvo', 'Benz', 'Toyota'];
$scope.myCar = "";
var carURL = {
Volvo: 'volvo.png',
Benz: 'benz.png',
Toyota: 'toyota.png'
};
$scope.getCarURL = function(brand) {
return carURL[brand];
}
and in the html:
<select ng-model="myCar">
<option ng-repeat="car in cars" value="{{car}}">{{car}}</option>
</select>
<img ng-src="{{getCarUrl(myCar)}}">
Select inputs in Angular are a bit confusing at first, but here is one way to set it up.
angular
.module('app',[])
.controller('AppCtrl',AppCtrl);
function AppCtrl() {
var vm = this;
vm.car_image = null;
vm.cars = [
{
'url':'audi.jpg',
'name':'Audi'
},
{
'url':'bmw.jpg',
'name':'BMW'
}
]
}
<div ng-controller="AppCtrl as ctrl">
<select ng-model="ctrl.car_image" ng-options="c.url as c.name for c in ctrl.cars" class="form-control"></select>
<hr>
<img ng-src="images/{{ctrl.car_image}}" ng-show="ctrl.car_image">
</div>
Using ng-src will prevent a 404 error initially when the page loads. So when you select the option you need, the ng-model from the select input is applied to the image tag.
Related
I have the below code in jQuery. I want to know what is the equivalent code of above in Angular Js 1.x Versions?
<select id="select">
<option value="1" data-foo="dogs">this</option>
<option value="2" data-foo="cats">that</option>
<option value="3" data-foo="gerbils">other</option>
</select>
// JavaScript using jQuery
$(function() {
$('select').change(function() {
var selected = $(this).find('option:selected');
var extra = selected.data('foo');
});
});
var sel = document.getElementById('select');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-foo');
You don't need to use jQuery when you are using angularjs.
To get the selected value in dropdown, you need to model select with ng-model and then the value will be there on the fly. That's the beauty of angularjs.
Moreover, if you are interested to add options on fly, better use ng-repeat to do that. And push in the array when you need to add another option. The option will be added to select. Another piece beauty of angularjs
Here
angular.module('app',[]).controller('ctrl', function($scope){
$scope.options = [{value : 1, attr: "dogs" },{value : 2, attr: "cats" },{value : 3, attr: "gerbils" }];
$scope.data = $scope.options[0]
$scope.select = 1;
$scope.add = function(){
$scope.options.push({value : $scope.options.length + 1, attr: 'option'})
};
$scope.getFoo = function(){
$scope.data = $scope.options.find(o=> o.value == $scope.select)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl'>
<select id="select" ng-model="select" ng-change="getFoo()">
<option ng-repeat="option in options" value="{{option.value}}" data-foo="{{option.attr}}">{{option.attr}}</option>
</select>
<button ng-click="add()">Add option</button>
{{data.value}}
{{data.attr}}
</div>
Add the value to the model that is provided as the data source for ng-repeat and set ng-model for dropdown .And get value of dropdown using ng-model.
When I reload the page, the first option is always empty. I want the option containing text Any Make to be the default select option. Here is the code for my view:
<select class="form-control" id="make" name="make" ng-init="Any Make" ng-model="makeSelected" ng-change="makeChanged()">
<option value="0" selected="selected"> Any Make</option>
<option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
</select>
here is my controller code:
.controller("homeController", function ($scope, makeData, $http) {
$scope.makeData = makeData;
$scope.makeChanged = function () {
$http({
method: "GET",
url: "homeService.asmx/GetModelById"})
.then(function (response) {
$scope.modelData = response.data;
})
}
})
just remove ng-init and in your model give default value
$scope.makeSelected = 0;
Here is a running fiddle for your code Click here
Fiddle for code with dynamic data Click here
If you aren't going to use ngOptions, at least get rid of that ng-init since it isn't a function, and in the controller function set $scope.makeSelected = 0;
Then you can remove the selected="selected" on that initial option, since the angularJS code will be handling what is selected.
See a demonstration below:
angular.module('app', [])
.value('makeData', [{
"make_id": 1,
"make_name": "cat"
},{
"make_id": 2,
"make_name": "dog"
},{
"make_id": 6,
"make_name": "monkey"
}])
.controller("homeController", function($scope, makeData, $http) {
//initialize the value associated with ng-model on the select list
$scope.makeSelected = 0;
$scope.makeData = makeData;
$scope.makeChanged = function() {
console.log('makeChanged');
//$http() request removed because we don't have access outside this domain for AJAX requests.
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="homeController">
<select class="form-control" id="make" name="make" ng-model="makeSelected" ng-change="makeChanged()">
<option value="0"> Any Make</option>
<option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
</select>
<div>makeSelected: {{makeSelected}}</div>
</div>
I have been working on this way too long trying to figure it out.
<select class="form-control"
ng-model="question.sel"
ng-change="updateDropDownQuestion(question,question.sel)">
<option ng-repeat="answer in question.answers" ng-disabled="answer.notAnOption" value="{{answer.acode}}">{{answer.name}}</option>
<option style="display:none" value="NONE">NONE</option>
</select>
Then in my js file:
$scope.updateDropDownQuestion = function(question, answer) {
reset(question.code)
$scope.formData["SOLE/SELECTED_QUESTION"] = question.code
$scope.formData["SOLE/SELECTED_ANSWER"] = answer
$scope.formData[question.code+"/"+answer] = true
var questions = $scope.product.questions
for(i=0; i <questions.length;i++){
if(questions[i].code == question.code){
questions[i].sel = answer
break;
}
}
$scope.refresh()
};
the $scope.refresh() is where it changes back. This renders the screen.
no matter what I do it seems to render the previous state and not the current state of the drop down. This is because I am repainting the screen after the drop down changes.
It seems as though the when the screen repaints it is taking the original value first.
Any thoughts on how I can get the value to "stick" once set?
Do I need to fire some event afterwards?
From Angular official site:
Note: ngModel compares by reference, not value. This is important when binding to an array of objects. You might find this helpful to set the default values of your drop down. See an example below.
angular.module('demoApp', []).controller('DemoController', function($scope) {
$scope.options = [
{ label: 'one', value: 1 },
{ label: 'two', value: 2 }
];
// Although this object has the same properties as the one in $scope.options,
// Angular considers them different because it compares based on reference
$scope.incorrectlySelected = { label: 'two', value: 2 };
// Here we are referencing the same object, so Angular inits the select box correctly
$scope.correctlySelected = $scope.options[1];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="demoApp">
<div ng-controller="DemoController">
<div>
<h2>Incorrect</h2>
<p>We might expect the select box to be initialized to "two," but it isn't because these are two different objects.</p>
<select ng-model="incorrectlySelected"
ng-options="opt as opt.label for opt in options">
</select>
The value selected is {{ incorrectlySelected.value }}.
</div>
<div>
<h2>Correct</h2>
<p>Here we are referencing the same object in <code>$scope.correctlySelected</code> as in <code>$scope.options</code>, so the select box is initialized correctly.</p>
<select ng-model="correctlySelected"
ng-options="opt as opt.label for opt in options">
</select>
The value selected is {{ correctlySelected.value }}.
</div>
</div>
</body>
Try using ng-options to render option elements.
Something along these lines:
<select class="form-control"
ng-model="question.sel"
ng-change="updateDropDownQuestion(question,question.sel)"
ng-options="answer.acode as answer.name in question.answers">
</select>
It also depends on what updateDropDownQuestion is doing, can you provide that?
I want to set the tags in in drop down usning select2. Like i want to put custom e-mail or anything else then it should show as tag.
I am sharing the jsfiddle.
<div ng-controller="MyCtrl">
<label>Please select items:</label>
<select ui-select2 multiple ng-model='selectedDaltons'>
<option ng-repeat="d in daltons" ng-bind="d" value="{{ d }}"></option>
</select>
</div>
var myApp = angular.module('myApp', ['ui.select2']);
function MyCtrl($scope) {
$scope.daltons = [
'Joe',
'William' ,
'Jack' ,
'Averell' ,
'Ma'
];
$scope.selectedDaltons = 'joe'; // Averell is preselected
};
http://jsfiddle.net/hWXBv/179/
In ui-select, you can use the 'tagging' feature, you can even set the tagging-label.
Check out this link
https://github.com/angular-ui/ui-select/wiki/ui-select
And this plunker:
http://plnkr.co/edit/m1SQXUxftBLQtitng1f0
What is the simplest way to add some commands to the end of the Angular select box?
E.g. I want to get a list like this:
Cat
Dog
Octopus
Browse…
All items except Browse are some data / ng-options, but Browse is a command and always present. It should not be actually selectable as an item, and should call a handler instead.
I suppose I could put this command into the list bound to ng-options and manage it as a special case, but that feels like a hack. Is there a proper approach to this?
Take a look at this, here when you select the browse it will open a dialog box
Working Demo
html
<form ng-app="app" ng-controller="Ctrl" ng-init="item = this">
<select ng-model="animal" ng-change="clickToOpen()" ng-init="animal='select'">
<option value="select">Please select an animal</option>
<option ng-repeat="animal in animalsGroup">{{animal.name}}
</option>
<option value="Browse..">Browse..</option>
</select>
<script type="text/ng-template" id="templateId">
<h1>Template heading</h1>
<p>Content goes here</p>
<center><input type="button" value="OK" ng-click="closeThisDialog(this)"/></center>
</script>
</form>
script
var app = angular.module("app", ['ngDialog']);
app.controller('Ctrl', function ($scope, ngDialog) {
$scope.animalsGroup = [
{name:'Cat'},
{name:'Dog'},
{name:'Octopus'}
];
// select initial value
$scope.animal = $scope.animalsGroup[0];
//
$scope.clickToOpen = function () {
if ($scope.animal === 'Browse..')
{
$scope.animal = "select";
ngDialog.open({
template: 'templateId',
className: 'ngdialog-theme-plain',
showClose: false,
});
}
else
{
// other than 'Browse'
}
};
$scope.closeThisDialog = function (dialog) {
dialog.close();
}
});
If i understood corectly you want to handle the browse option differently .
Script :
$scope.colors = [
{name:'Cat'},
{name:'Dog'},
{name:'Octopus'},
{name:'Browse'}
];
$scope.handleChange = function(){
if ($scope.myColor.name === 'Browse'){
// your implementation
}
}
Html :
<select ng-model="myColor" ng-options="color.name for color in colors" ng-change="handleChange"></select>