How to change select options from js in this example - javascript

How can I select the tag option from the javascript/Angularjs backend.
Hint: I actually get data from API service, then I fill into a form to make them available for edit. Assume the gender is Male, how can I make the tage becomes Male as it is in databse. So user can update it to Female for example.
Here is my codes:
$scope.Gender = [
{ GenderID: "Mmale", name: "Mmale" },
{ GenderID: "Female", name: "Female" }
];
HTML
<select class="form-control" name="Gender" ng-model="GenderID" ng-options="g.GenderID as g.name for g in Gender" required style="width:98px; color:gray">
<option value="" style="" >Gender?</option>
</select>
Currently I use this to change the option but it does not work for me.
$scope.Gender.name = $scope.users[id].Gender;
$scope.Gender.GenderID = $scope.users[id].Gender;

Here is a working JSFiddle, you only need to give the ng-model the GenderID you want to select:
HTML:
<div ng-app ng-controller="MyCtrl">
<select class="form-control" name="Gender" ng-model="GenderID" ng-options="g.GenderID as g.name for g in Gender" required style="width:98px; color:gray">
<option value="" style="" >Gender?</option>
</select>
</div>
JS:
function MyCtrl($scope, $filter) {
$scope.Gender = [
{ GenderID: "Mmale", name: "Mmale" },
{ GenderID: "Female", name: "Female" }
];
$scope.GenderID = "Mmale";
}

Related

How to set array objects int json object with AngularJS?

i want load array objects from multi select control, then i want load model object called "name" with his name and age values, then i want load array from select and load in model object.... but the ng-model from select control not work :/
<input type="text" class="form-control" ng-model="model.name" placeholder="Put your name..." />
<input type="text" class="form-control" ng-model="model.age" placeholder="Put your age..." />
<!--Select pets for model person-->
<select ng-repeat="pets in arrayFromApi" class="selectpicker" multiple>
<option id="{{pet.id}}" ng-model="model.pets.id">{{pet.name}}</option>
</select>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.model = { "name":"", "age":"", "pets" :[ {"id":""} ] };
$scope.arrayFromApi = function() {
......
this function get id names
}
});
</script>
You will probably need to use ng-options.
You can give it a try with ng-repeat but then it should be on option tag only.
Avoid using ng-repeat on the dropdowns, it casuses some performance issues. instead use ng-options.
And for havint the model with name, age and pets. check the mixData funciton.
<input type="text" class="form-control" ng-model="model.name" placeholder="Put your name..." />
<input type="text" class="form-control" ng-model="model.age" placeholder="Put your age..." />
<!--Avoid ng-repeat in dropdowns-->
<!--Select pets for model person-->
<select ng-change="mixData()" class="selectpicker" multiple ng-model="myPets" ng-options="pet.id as pet.name for pet in arrayFromApi">
<option value="">Select...</option>
</select>
<!--<select ng-repeat="pets in arrayFromApi" class="selectpicker" multiple>
<option id="{{pet.id}}" ng-model="model.pets.id">{{pet.name}}</option>
</select>-->
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.model = { "name":"", "age":"", "pets" :[ {"id":""} ] };
$scope.arrayFromApi = function() {
......
this function get id names
}
$scope.mixData = function(){
$scope.model.pets = $scope.myPets;
};
});
</script>
It's much better if you use select as angular standards ng-options with this attribute you can handle everything in your view and multiple type return array to your controller as {id: n}
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.model = {};
//from api
$scope.arrayFromApi = [{
id: 1,
name: 'test'
},
{
id: 2,
name: 'test2'
}
];
$scope.getDetails = function() {
console.log($scope.model);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="model.name" placeholder="Put your name..." />
<input type="text" ng-model="model.age" placeholder="Put your age..." />
<!--Select pets for model person-->
<select ng-model="model.pets" ng-options="{id: item.id} as item.name for item in arrayFromApi" multiple></select>
<button ng-click="getDetails()">save</button>
</div>

Blank HTML SELECT without blank item in dropdown list in angular

Problem: I have form that works fine. However, I am not able to set a blank item to appear in the dropdown list.
I am new to both angular and javascript and I have not been able to figure it out.
I have the following line of code:
$scope.miles = [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }];
and here is the form:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" ">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles" required>
<option selected disabled hidden style='display: none' value=''></option><!---<option >5</option><option>10</option><option>15</option><option>20</option>--->
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" onclick="return checkTextField()" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search"/></div>
</form>
</div>
</div>
How would I set a blank item to appear but have the value: 5 be the default value when I run the form. So when the user enters the page, the miles is set blank but will still generate a result when the user enters a name of a hospital and city. If users enters zip code, it will generate an alert.
Update I have tried the following as suggested by Sibi Raj to do the following:
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" required>
<option selected disabled value=''></option>
<option ng-repeat="data in miles" value={{data.value}}>{{data.value}}</option>
</select>
Works fine however it creates an extra line:
and when I inspect, I get this weird value populating:
How would I remove that unknown blank space?
UPDATE
Thanks to Sibi Saj, I was able to create a blank space to appear in the textbox and still have results appear when the user enters a hosptial name and city location.
However, when I enter a zip code and select a range, meaning miles, rather then showing a hospital within the mileage, it will show the whole results.
The following is the script that Sibi Saj helped me with:
var myApp = angular.module('myApp', []);
// Controller
myApp.controller('demoController', ['$scope', function($scope) {
$scope.searchParam = {
distance: 5 //set the value to the select box
}
$scope.miles = [{
'value': '5'
}, {
'value': '10'
}, {
'value': '15'
}, {
'value': '20'
}];
}])
// directive that converts number-string to number
myApp.directive('convertToNumber', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(val) {
return val != null ? parseInt(val, 10) : null;
});
ngModel.$formatters.push(function(val) {
return val != null ? '' + val : null;
});
}
};
});
How would I get results to appear that are within the miles based on the zip code?
You can try to put an option inside the repeat:
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles" required>
<option selected disabled hidden style='display: none' value=''>
<option value="5"></option>
</option>
</select>
instead of ng options, you could use ng-repeat
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" required>
<option selected disabled value=''>Select</option>
<option ng-repeat="data in miles" value={{data.value}}>{{data.value}}</option>
</select>
Add the convert to number directive to your code "convert-to-number" in the select element
In HTML
<select class="form-control" id="miles" name="distance" ng-model="searchParam.distance" required convert-to-number>
<option value="">Select Me</option>
<option value={{v.value}} ng-repeat="(k , v) in miles track by $index">{{v.value}}</option>
Script(don't forget to add the directive)
var myApp = angular.module('myApp', []);
// Controller
myApp.controller('demoController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
$scope.searchParam = {
distance: 5 //set the value to the select box
}
$scope.miles = [{
'value': '5'
}, {
'value': '10'
}, {
'value': '15'
}, {
'value': '20'
}];
}])
// directive that converts number-string to number
myApp.directive('convertToNumber', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(val) {
return val != null ? parseInt(val, 10) : null;
});
ngModel.$formatters.push(function(val) {
return val != null ? '' + val : null;
});
}
};
});
here is the plunker https://plnkr.co/edit/srCJAgJ9fnOnbVzp5FL3?p=preview

using ng-show on option select angularjs

I want to bind my input field to my select option. so if the select option is Yes, the input field should be visible and if it is No, the input field should be hidden.
(function(){
var app = angular.module('spa',[
$rootScope.options = [
{
id: 0,
name: 'No'
},
{
id: 1,
name: 'Yes'
}
]
]);
}());
<form name="newData" class="ng-scope ng-pristine ng-invalid ng-invalid-required" error-popup="newData" novalidate>
<div class="form-group item item-input item-select">
<div class="input-label">
Booking Fee Paid
</div>
<select name="booking" ng-model="user.booking" class="form-control ng-pristine ng-invalid ng-invalid-required" ng-options="option.name for option in options track by option.id" ng-init ="user.booking = options[0]" required>
</select>
</div>
<div class="row" ng-show="user.booking.name == 'Yes'">
<div class="col">
<div class="form-group item item-input">
<input type="text" name="amount" ng-model="user.amount" class="form-control" placeholder="Amount">
</div>
</div>
</div>
</form>
http://plnkr.co/edit/v0NrbTeigo3lm1njRu9A?p=preview
Any help is appreciated
I suggest you to go through the beginner tutorials # angularjs.org.
Here is a working sample that does just what you're asking for:
angular.module('app', [])
.controller('Sample', Sample);
function Sample() {
this.options = [{
id: 0,
name: 'No'
}, {
id: 1,
name: 'Yes'
}];
this.booking = this.options[0];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Sample as vm">
<select name="booking" ng-model="vm.booking" ng-options="option.name for option in vm.options"></select>
<pre>{{ vm.booking | json }}</pre>
<input type="text" ng-show="vm.booking.name === 'Yes'"/>
</div>
Second parameter specifies required modules not the implementation:
angular.module(name, [requires], [configFn]);
So you had inject error. Here is the fixed code:
http://plnkr.co/edit/L02U4Cq0HIqeLL1AOcbl
var app = angular.module('spa', []);
app.controller('MyController', function($scope) {
$scope.options = [{
id: 0,
name: 'No'
}, {
id: 1,
name: 'Yes'
}];
});

ember: related model appears in chrome inspecter but empty in template

I've got the following code that successfully loads a garment. Chrome ember inspector shows that both Garment and its related model have loaded but I can't seem to display the related model (garment_colors) in the template.
Would really appreciate any help!
{{log garment_colors}} logs an empty array Class {type: function, content: Array[0], store: Class, _changesToSync: OrderedSet, loadingRecordsCount: 0…}__ember1410723197678: "ember522"__ember_meta__: Object__nextSuper: undefined_changesToSync: OrderedSetcontent: Array[0]isLoaded: trueisPolymorphic: undefinedloadingRecordsCount: 0name: "garment_colors"owner: Classstore: ClasstoString: function () { return ret; }type: App.GarmentColor__proto__: Object ember-1.7.0.js:14463
var attr = DS.attr,
belongsTo = DS.belongsTo,
hasMany = DS.hasMany;
App.Garment = DS.Model.extend({
name: attr(),
brand: attr(),
description: attr(),
materials: attr(),
garment_colors: hasMany('garmentColor')
});
App.GarmentColor = DS.Model.extend({
name: attr(),
color: attr(),
garment: belongsTo('garment')
});
App.DesignerRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('garment',params.id);
},
setupController: function(controller, model) {
controller.set('content', model)
console.log(model);
},
});
My json
{
"garment":{
"id":2,
"name":"Ultra shirt",
"brand":"Gildan",
"description":"this is the description",
"materials":"5.6 oz. 50% preshrunk cotton, 50% polyester.",
"garment_color_ids":[
66,
67,
68
]
},
"garment_colors":[
{
"id":66,
"name":"Purple",
"color":"#4f237a"
},
{
"id":67,
"name":"Light Blue",
"color":"#89b4df"
},
{
"id":68,
"name":"Carolina Blue",
"color":"#91b0e6"
}
]
}
Template - other attributes like name and brand display properly.
<script type="text/x-handlebars" data-template-name="designer">
{{outlet}}
<div id="product-details">
<h4>Style</h4>
<p id="name">{{name}}</p>
<p id="brand">{{brand}}</p>
<p id="description">{{description}}</p>
<p id="materials">{{materials}}</p>
<h4>Color</h4>
{{log garment_colors}}
<div id="color-list">
{{#each garment_colors}}
<label class="btn" style="background-color:{{color}}">
<input type="radio" name="color" value="{{name}}">
</label>
{{/each}}
</div>
</div>
</script>
The RESTAdapter expects the attribute name to be garment_colors.
"garment_colors":[
66,
67,
68
]
Adding in values like this isn't supported in handlebars, depending on certain versions it will add metamorph tags into the html.
<label class="btn" style="background-color:{{color}}">
<input type="radio" name="color" value="{{name}}">
</label>
You'll either need to make it unbound, which will inject it right into the template, but won't be bound to the model.
<label class="btn" style="background-color:{{unbound color}}">
<input type="radio" name="color" value="{{unbound name}}">
</label>
Or you'll need to use bind-attr to bind the attribute to the property
<label class="btn" {{bind-attr style=someProperty}}>
<input type="radio" name="color" {{bind-attr value=name}}>
</label>
Example: http://emberjs.jsbin.com/OxIDiVU/1077/edit

comparing values from two different context using mustache and canjs

Lets say I have this mustache template below. contacts and categories are basically an array of objects:
<script type="text/mustache" id="contactsList">
<ul class="clearfix">
{{#contacts}}
<li class="contact span8">
<i class="icon-remove"></i>
<form>
<div class="row">
<div class="span2">
<img src="img/canjs.jpg" width="100" height="100">
</div>
<div class="span3">
<input type="text" name="name" placeholder="Add Name" value="{{name}}">
<select name="category">
{{#categories}}
<option value="{{data}}" {{sameCategory category data}}>
{{name}}
</option>
{{/categories}}
</select>
</div>
<div class="span3">
<label>Address</label>
<input type="text" name="address" value="{{address}}">
<label>Phone</label>
<input type="text" name="phone" value="{{phone}}">
<label>Email</label>
<input type="text" name="email" value="{{email}}">
</div>
</div>
</form>
</li>
{{/contacts}}
</ul>
</script>
What I want to do is generate "selected" within the option tag by comparing the contacts|category and categories|data.
so what I did was to implement the sameCategory like this:
can.Mustache.registerHelper('sameCategory', function(contactCategoryId, categoryId) {
console.log(contactCategoryId);
console.log(categoryId);
var result = contactCategoryId == categoryId ? "selected" : "";
console.log(result);
return result;
});
Unfortunately, im getting an object for both param instead of strings so my equality condition fails. What am I doing wrong? is there a better way to do this besides registerhelper?
supporting data:
var CONTACTS = [
{
id: 1,
name: 'William',
address: '1 CanJS Way',
email: 'william#husker.com',
phone: '0123456789',
category: 'co-workers'
},
{
id: 2,
name: 'Laura',
address: '1 CanJS Way',
email: 'laura#starbuck.com',
phone: '0123456789',
category: 'friends'
},
{
id: 3,
name: 'Lee',
address: '1 CanJS Way',
email: 'lee#apollo.com',
phone: '0123456789',
category: 'family'
}
];
var CATEGORIES = [
{
id: 1,
name: 'Family',
data: 'family'
},
{
id: 2,
name: 'Friends',
data: 'friends'
},
{
id: 3,
name: 'Co-workers',
data: 'co-workers'
}
];
I took these code from the examples Diving into CanJS article.
I was checking out your code on a fiddle, and I couldn't replicate it, though perhaps you were getting can.computes that you would need to run as function before you got the values.
However, that said, the helper is entirely unnecessary with the can/view/bindings plugin. Just set can-value="category" on your select and it will auto-magically select the correct option (and update the value when changed).
Demonstrated in a fiddle: http://jsfiddle.net/air_hadoken/g725X/1/
<select name="category" can-value="category">
{{#categories}}
<option value="{{data}}" >
{{name}}
</option>
{{/categories}}
</select>

Categories

Resources