I'm trying to show or hide a div based on a selection from a list. I'm not quite sure how to handle the observable for the div being passed to a function so it can return a true or false value to show or hide the div.
If "American Express" is selected from the list, I want to display the "postalCodeDiv", otherwise hide it.
I have a fiddle for it here
<label for="Card Type">Card Type</label>
<select data-bind='value: cardType, options: $root.cardTypeList, optionsText: "type"'>
</select>
<div data-bind="visible: postalCodeDiv()">
<label for="PostalCode">Postal Code (required for AMEX)
</label>
</div>
Here's the javascript
function cardTypeSelection(cardType,postalCodeDiv){
var self = this;
self.cardType = cardType;
self.postalCodeDiv = postalCodeDiv;
if(self.cardType == "American Express"){
return self.postalCodeDiv(true);
}
else{
return self.postalCodeDiv(false);
}
}
function MakePaymentViewModel(cardType) {
var self = this;
self.postalCodeDiv = ko.observable(false);
self.cardTypeList = [
{type: '-'},
{type: 'Visa'},
{type: 'MasterCard'},
{type: 'American Express'}
];
self.cardType = ko.observableArray([
new cardTypeSelection(self.cardTypeList[0], self.postalCodeDiv)
]);
}
ko.applyBindings(new MakePaymentViewModel());
And upon selection of it, I pass it to a function to enable/disable based on the value of the selection
i think you can have it much easier than you tried. not quite sure why you try to store the selected value from the dropdown into an array, you could just store the selected value into an observable and toggle the div visibility upon this.
jsFiddle
ViewModel:
function MakePaymentViewModel(cardType) {
var self = this;
self.cardTypeList = [
{type: '-'},
{type: 'Visa'},
{type: 'MasterCard'},
{type: 'American Express'}
];
self.cardType = ko.observable(self.cardTypeList[1]);
}
ko.applyBindings(new MakePaymentViewModel());
HTML:
<label for="Card Type">Card Type</label>
<select data-bind='value: cardType, options: $root.cardTypeList, optionsText: "type"'>
</select>
<div data-bind="visible: cardType() == cardTypeList[3]">
<label for="PostalCode">Postal Code (required for AMEX)
</label>
</div>
As an alternative to the accepted answer provided by #infadelic, here is an example using a computed observable. If you need this logic in more than one place, you may want to put it in your viewModel as a computed observable instead of having the logic repeated in multiple bindings.
Fiddle: http://jsfiddle.net/6ymwN/12/
ViewModel
function MakePaymentViewModel(cardType) {
var self = this;
self.postalCodeDiv = ko.observable(false);
self.cardTypeList = [
{type: '-'},
{type: 'Visa'},
{type: 'MasterCard'},
{type: 'American Express'}
];
self.cardType = ko.observableArray([
new cardTypeSelection(self.cardTypeList[0], self.postalCodeDiv)
]);
self.selectedCardType = ko.observable();
self.isAmex = ko.computed(function(){
var card = self.selectedCardType();
return card == 'American Express';
});
}
HTML
<label for="Card Type">Card Type</label>
<select data-bind='value: cardType, options: $root.cardTypeList, optionsText: "type", optionsValue: "type", value: selectedCardType'>
</select>
<div data-bind="visible: isAmex()">
<label for="PostalCode">Postal Code (required for AMEX)
</label>
</div>
Related
I have a dropdown with some values :
Apple
Mango
Orange
Grapes
HTML :
<div class="form-group">
<label class="control-label col-sm-20" for="groupz">Role*</label>
<select class="form-control" ng-model="model.selectedRole" name="role" ng-change="GetRole(model.selectedRole)" >
<option value class selected>Select Roles</option>
<option ng-repeat="item in model.roles track by $index" value="{{item}}">{{item}}</option>
</select>
</div>
I want my $scope.selectedRole to be by default as Apple. But later when the user needs to change the value, they can change it from apple to orange or any other fruit name. I have separate service request to fetch the fruits from backend and I write my code in controller as follows.
$scope.GetRole = function() {
$scope.selectedrole = [];
if ($scope.model.selectedRole != null) {
for (var i = 0; i < 1; i++) {
$scope.selectedrole.push($scope.model.selectedRole);
}
}
}
I hope this helps you
JsFiddle
In js
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.selectedrole = ['Apple', 'Mango', 'Orange', 'Grapes'];
$scope.selectRole= $scope.selectedrole[0];
});
In HTML
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<select ng-model="selectRole" ng-options="role for role in selectedrole">
</select>
</div>
just try : HTML
<select class="form-control select" name="role" id="role" data-ng-model="ctrl.model.selectedRole" data-ng-options="option.name for option in ctrl.model.roles track by option.id"></select>
in your contoller
$scope.model = {
roles: [{
id: '1',
name: 'Apple'
}, {
id: '2',
name: 'Orange'
}, {
id: '3',
name: 'Mango'
}],
selectedRole: {
id: '1',
name: 'Apple'
} //This sets the default value of the select in the ui
};
Then assign the first array element to selectedrole containing the array of values(Apple Mango Orange Grapes).
If you want the default to be apple and the array is ordered:
array = [Apple, Mango, Orange, Grapes]
Your model needs to be set to selectedRole:
data-ng-model="selectedRole"
In your controller, set:
selectedRole = array[0]
angular will take care of the rest of the data manipulation.
I hope this helps. Please provide more information for a clearer answer
Thanks
Handling a select element i.e. a drop down list in AngularJS is pretty simple.
Things you need to know is that you bind it to an array or a collection to generate the set of option tags using the ng-options or the ng-repeat directives which is bound to the data source on your $scope and you have a selected option which you need to retrieve as it is the one the user selects, it can be done using the ng-model directive.
If you want to set the selected option on the page load event, then you have to set the appropriate object or value (here it is the fruit id) which you are retrieving from data binding using the as clause in the ng-options directive as shown in the below embedded code snippet
ng-options="fruit.id as fruit.name for fruit in ctrl.fruits"
or set it to the value of the value attribute when using the ng-repeat directive on the option tag i.e. set data.model to the appropriate option.value
<select size="6" name="ngvalueselect" ng-model="data.model" multiple>
<option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
</select>
angular
.module('fruits', [])
.controller('FruitController', FruitController);
function FruitController() {
var vm = this;
var fruitInfo = getFruits();
vm.fruits = fruitInfo.fruits;
vm.selectedFruitId = fruitInfo.selectedFruitId;
vm.onFruitChanged = onFruitChanged;
function getFruits() {
// get fruits and selectedFruitId from api here
var fruits = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Mango' },
{ id: 3, name: 'Banana' },
{ id: 4, name: 'Orange' }
];
var fruitInfo = {
fruits: fruits,
selectedFruitId: 1
};
return fruitInfo;
}
function onFruitChanged(fruitId) {
// do something when fruit changes
console.log(fruitId);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fruits">
<div ng-controller="FruitController as ctrl">
<select ng-options="fruit.id as fruit.name for fruit in ctrl.fruits"
ng-model="ctrl.selectedFruitId"
ng-change="ctrl.onFruitChanged(ctrl.selectedFruitId)">
<option value="">Select Fruit</option>
</select>
</div>
</div>
Check the Example section here for more information.
I have a problem when implementing a nested list in Angular: the view gets updated properly but, on the other side, the code is not updated on change.
I think it will be much clearer with the code:
_this.categories = injections.map(function (category) {
return {
title: category.get('title'),
object: category,
criteria: category._criteria.map(function (oneCriteria) {
return {
object: oneCriteria,
type: oneCriteria.get("type"),
min: _this.range(oneCriteria.get("range")).min,
max: _this.range(oneCriteria.get("range")).max,
key: oneCriteria.get("key"),
value: _this.range(oneCriteria.get("range")).min,
defaultValue: _this.range(oneCriteria.get("range")).min,
selected: false
}
})
}
});
_this.category = _this.categories[0];
_this.job = {
title: '',
description: '',
salaryAmount: 0,
salaryTimeUnit: _this.salaryTimeUnits[0],
category: _this.category.object,
criteria: _this.category.criteria,
location: {latitude: 48.137004, longitude: 11.575928}
};
So and, very quick here is my HTML:
<div ng-repeat="category in controller.categories">
<input type="radio" name="group" ng-value="category.object.get('title')" id="{{category.object.get('title')}}"
ng-checked="controller.category == category" ng-click="controller.category = category">
{{category.title}}
</div>
<br>
Criteria:
<div ng-repeat="criterium in controller.category.criteria">
<div class="row vertical-align">
<div class="col-xs-9">
<span ng-click="criterium.selected = !criterium.selected"
ng-class="['list-group-item', {active:criterium.selected == true}]">{{criterium.key}}</span>
</div>
</div>
</div>
The problem is the following: the value are getting updated in the view (when you click on a radio button on the category, you see the corresponding criteria(s)). But the job is for one reason that I ignore not updated although it has the same reference as the HTML (a reference to this category.criteria).
Did I miss something?
controller.job.criteria is still just a reference to controller.categories[0]. Your code should successfully update controller.category to point at whichever category you clicked on, but that does not also update the reference in your job data structure.
What you want to do is make your ngClick event a bit more robust, i.e.:
<input type="radio" ng-click="controller.updateCategory(category)" />
and then in your js:
_this.updateCategory = function (category) {
_this.category = category;
_this.updateJob(category);
};
_this.updateJob = function (category) {
_this.job.category = category.object;
_this.job.criteria = category.criteria;
};
This will update the references in your job to match the new jazz.
I would, however, recommend leveraging ngModel and ngChange in your radios instead. Like:
<input type="radio" ng-model="controller.category" ng-value="category" ng-change="updateJob(category)" /> {{category.title}}
I have an issue with Knockout.js . What I try to do is filter a select field. I have the following html:
<select data-bind="options: GenreModel, optionsText: 'name', value: $root.selectedGenre"></select>
<ul data-bind="foreach: Model">
<span data-bind="text: $root.selectedGenre.id"></span>
<li data-bind="text: name, visible: genre == $root.selectedGenre.id"></li>
</ul>
And the js:
var ViewModel = function (){
self.selectedGenre = ko.observable();
self.Model = ko.observableArray([{
name: "Test",
genre: "Pop"
}
]);
self.GenreModel = ko.observableArray([
{
name: "Pop",
id: "Pop"
},
{
name: "Alle",
id: "All"
}
]);
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
JSFiddle: http://jsfiddle.net/CeJA7/1/
So my problem is now that the select list does not update the binding on the span inside the ul and I don't know why...
The value binding should update the property selectedGenre whenever the select value changes, shouldn't it?
Any ideas are welcome.
There are a lot of issues in your code:
1) self is not a magical variable like this. It's something people use to cope with variable scoping. Whenever you see self somewhere in a JavaScript function be sure there's a var self = this; somewhere before.
2) KnockoutJS observables are not plain variables. They are functions (selectedGenre = ko.observable()). ko.observable() returns a function. If you read the very first lines of documentation regarding observables you should understand that access to the actual value is encapsulated in this retured function. This is by design and due to limitations in what JavaScript can and cannot do as a language.
3) By definition, in HTML, <ul> elements can only contain <li> elements, not <span> or anything else.
Applying the above fixes leads to this working updated sample:
HTML:
<select data-bind="options: GenreModel, optionsText: 'name', value: selectedGenre"></select>
<span data-bind="text: $root.selectedGenre().id"></span>
<ul data-bind="foreach: Model">
<li data-bind="text: name, visible: genre == $root.selectedGenre().name"></li>
</ul>
JavaScript:
var ViewModel = function (){
var self = this;
self.selectedGenre = ko.observable();
self.Model = ko.observableArray([
{
name: "Test",
genre: "Pop"
}
]);
self.GenreModel = ko.observableArray([
{
name: "Pop",
id: "Pop"
},
{
name: "Alle",
id: "All"
}
]);
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
I have a drop down list that is bound to a SelectedFormat value. The lists options are populated from external source on load and matches the view models data.Format object base on id.
Take a look at the js fiddle
Can anyone tell me why the model updates but the UI is not updating with the correct Format.Name
Thanks.
HTML:
<div data-bind="text:data.Format.Name"></div>
<select data-bind="
options:Controls,
optionsText: 'Name',
value: data.SelectedFormat"></select>
Model:
var jsonData = {
Id: "abc-123",
Name: "Chicken Cheese",
Format: {
Id: 2,
Name: 'Medium',
Other: 'Bar'
}
};
var self = this;
self = ko.mapping.fromJS(data);
self.SelectedFormat = ko.observable(
//return the first match based on id
$.grep(vm.Controls,function(item){
return item.Id === self.Format.Id();
})[0]
);
//when changed update the actual object that will be sent back to server
self.SelectedFormat.subscribe(function (d) {
this.Format = d;
},self);
In your code, you have Format and SelectedFormat. The former isn't an observable and so can't trigger updates. You have to use SelectedFormat instead.
<div data-bind="text:data.SelectedFormat().Name"></div>
Example: http://jsfiddle.net/QrvJN/9/
I have this simple knockout.js application:
View:
<select data-bind="options: allDocumentTypes , optionsCaption: 'Choose ...', optionsValue: 'id', optionsText: 'name', selectedOptions: selectedDocument"></select>
<span data-bind="click: cl">CLEAR VALUE!</span>
and this simple ViewModel:
function documentType(id, name){
this.id = id;
this.name = name;
}
var viewModel = {
allDocumentTypes: ko.observableArray([]),
selectedDocument: ko.observable(''),
cl: function(){
viewModel.selectedDocument('');
}
};
/* load data */
viewModel.allDocumentTypes.push(new documentType(1,'Test 1'));
viewModel.allDocumentTypes.push(new documentType(2,'Test 2'));
ko.applyBindings(viewModel);
I would expect, that after i click on span "CLEAR VALUE!", in select will be selected option "choose...", but it is not happening.
The value in viewModel is set to "" (empty string), which is right, but user still see old value in select.
Is there any way to do that?
Thanks for helping:)
You must change binding type to "value" instead of "selectedOptions". Next step is to set viewModel.selectedDocument in cl function:
viewModel.selectedDocument(null);
In some cases setting the observable value to null will not work, for example :
// This is the array
self.timePeriods = ko.observableArray([
new timePeriod("weekly", 7),
new timePeriod("fortnightly", 14),
new timePeriod("monthly", 30),
new timePeriod("half yearly", 180),
new timePeriod("yearly", 365)
]);
And below is the HTML part:
<select data-bind="options: timePeriods,
optionsText: function(item) {
return item.Name;
},
value: selectedPeriod"
class="combo">
You can't reset select box by:
self.selectedPeriod(null); // but this will not work
Insetead write this:
self.selectedPeriod(self.timePeriods()[0]);
<script>
var vm ={
CountryId=ko.observable(),
QC=ko.observable(),
clearSelectedStation: function () {
this.CountryId(null); //DropDown
this.QC(''); //Textbox
}
};
</script>
here is a html
<input type="text" tabindex="10" data-bind="value:QC"/>
<select class="dropdownlist" data-bind="options:Countries, value: CountryId,
optionsCaption: '--Select--', optionsText: 'CountryName', optionsValue: 'CountryId'">