using ng-show on option select angularjs - javascript

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'
}];
});

Related

How to select rows based on string options in html vue js?

I need to add new rows based on the select options.
If my option is "kfc" I need to select a particular row. If my selected option is "cemrt", I need to add another row.
<div class="card-content" v-for="(bok, index) in rules" :key="index">
<div class="row">
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Booked</label>
<select class="form-control" v-model="bok.name">
<option value="SEENAT">SEENAT</option>
<option value="CEMRT">CEMRT</option>
<option value="KFC">KFC</option>
</select>
</div>
</div>
</div>
<div class="row" v-if="bok.name == SEENAT"> //NOT WORKING FROM HERE
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Arms(if any)</label>
<input type="text" class="form-control" v-model="bok.data.head" required="">
</div>
</div>
</div>
<div class="row" v-if="bok.name == KFC">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Arms(if any)</label>
<input type="text" class="form-control" required="">
</div>
</div>
</div>
</div>
But I am using this code not able to add rows based on the options.
My vue js code is
addForm = new Vue({
el: "#addForm",
data: {
rules : [{
name:null,
section:null,
data : [{head:null,value:null}]
}],
},
methods: {
addNewRules: function() {
this.rules.push({ name: null, section: null,data [{head:null,value:null}] });
},
},
});
If I use option value as 1,2,3 etc. I am getting the result.
But I need to send SEENAT,CEMRT,KFC as data. How can I able to achieve the result.
Hard to tell. A reproduction on codesandbox would be welcome.
What I can see in your code at a first glance :
1) You forgot quotes around the options keys and thus it expects a constant. The fact you're using double equals instead of triple doesn't help:
v-if="bok.name === 'SEENAT'" // this
v-if="bok.name == SEENAT" // instead of that
2) data should be a function:
data() {
return {
rules: [
{
name: null,
section: null,
data: [{ head: null, value: null }]
}
]
};
},

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

Angular js not retrieving value by id's for dropdowns

I have an angular app with the following function:
$scope.search= function(){
var lname = document.getElementById("lastname").value;
var campus2 = document.getElementById("campusid").value;
StudentSearchService.getStudents(lname, campus2, function(data){
if(data!=null){
$scope.students = data;
}
});
}
and in the html page, I have the following 2 fields:
<div class="form-group col-lg-4 col-md-4">
<label for="lastname"> Last Name: </label>
<input type="text" id="lastname" placeholder="Last Name" class="form-control" />
</div>
<div class="form-group col-lg-4 col-md-4">
<label for="campus"> Campus:</label>
<select class="form-control" id="campusid" ng-model="newcampus" ng-options="camp.name for camp in campus" >
<option value="">ALL - District</option>
</select>
</div>
When i click to Search, the value for the lname is being retrieved just fine but the value from the dropdown campus2 is not being being initialized. Thus the call to the service is not being made properly.
Where am I going wrong?
First, it is not necessary to pick values from DOM elements if you are using Angular. It is way more easier to bind variables and use the variables themselves. I have created your example in JSFiddle: http://jsfiddle.net/rmadhuram/1n14eqfw/2/
HTML:
<div ng-app="app" ng-controller="FormController">
<div class="form-group col-lg-4 col-md-4">
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" ng-model="lastName" placeholder="Last Name" class="form-control" />
</div>
<div class="form-group col-lg-4 col-md-4">
<label for="campus">Campus:</label>
<select class="form-control" id="campusid" ng-model="newcampus" ng-options="camp.name for camp in campus">
</select>
</div>
<button ng-click='search()'>Search</button>
</div>
JavaScript:
angular.module('app', [])
.controller('FormController', ['$scope', function ($scope) {
$scope.campus = [
{ name: 'campus 1' },
{ name: 'campus 2' }
];
$scope.newcampus = $scope.campus[0];
$scope.lastName = '';
$scope.search = function() {
alert('Name: ' + $scope.lastName + ' Campus: ' + $scope.newcampus.name);
};
}]);
Hope this helps!
The biggest place you are going wrong is by trying to access values directly from the DOM inside your Angular controller, rather than relying on Angular to bind properties on the scope to your inputs and handle all of that for you.
I have made a version in Plunkr that demonstrates the "Angular way" of approaching this.
The guts of the controller is:
app.controller('MainCtrl', function($scope, StudentSearchService) {
$scope.campus = [
{name: "Campus 1"},
{name: "Campus 2"}
];
$scope.searchParams = {
lastName: "",
campus: null
};
$scope.search = function() {
StudentSearchService.getStudents($scope.searchParams.lastName,
$scope.searchParams.campus.name,
function(data) {
if (data !== null) {
$scope.students = data;
}
});
}
});
And then your markup becomes:
<div class="form-group col-lg-4 col-md-4">
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" placeholder="Last Name" class="form-control" ng-model="searchParams.lastName" />
</div>
<div class="form-group col-lg-4 col-md-4">
<label for="campus">Campus:</label>
<select class="form-control" id="campusid" ng-model="searchParams.campus" ng-options="camp.name for camp in campus">
<option value="">ALL - District</option>
</select>
</div>
Note the use of ng-model to bind the inputs to scope properties. Also note there is no DOM access code in the controller. This makes it easier to test, and allows you to test your controller without any DOM at all. That is the core philosophy Angular is based around.

Clear form after submit

I am submitting a form - and adding the contents to an array, however whenever the item is added to the array, it is still bound to the form.
I would like to add the item, clear the form. Something like jquery's reset();
Here's my template:
<div class="col-xs-12" ng-controller="ResourceController">
<div class="col-md-4">
<h3>Name</h3>
</div>
<div class="col-md-8">
<h3>Description</h3>
</div>
<form class="form-inline" role="form" ng-repeat="item in resources">
<div class="form-group col-md-4">
<input type="text" class="form-control" value="{{ item.name }}"/>
</div>
<div class="form-group col-md-7">
<input type="text" class="form-control" value="{{ item.description }}"/>
</div>
</form>
<form class="form-inline" role="form" name="addResourceForm" ng-submit="addResource()">
<div class="form-group col-md-4">
<input type="text" class="form-control" name="name" ng-model="name" placeholder="Name"/>
</div>
<div class="form-group col-md-7">
<input type="text" class="form-control" name="description" ng-model="description" placeholder="Description"/>
</div>
<div class="form-group col-md-1">
<button type="submit" class="btn btn-default">Add</button>
</div>
</form>
</div>
And my controller:
(function(){
var app = angular.module('event-resources', []);
app.controller('ResourceController', function($scope){
$scope.addResource = function(){
$scope.resources.push(this);
}
var defaultForm = {
name : '',
description: ''
};
$scope.resources = [
{
name: 'Beer',
description: 'Kokanee'
},
{
name: 'Pucks',
description: 'Black Round Things'
}
]
});
})();
Use angular.copy() to copy the item data to the resources array, and then you can safely clear the item data. The angular.copy() makes a deep copy of the object, which is what you want.
Alternately, here is a simpler method, which doesn't use any extra method calls:
$scope.addResource = function() {
$scope.resources.push({
name: $scope.name, // recreate object manually (cheap for simple objects)
description: $scope.description
});
$scope.name = ""; // clear the values.
$scope.description = "";
};
$scope.addResource = function(){
$scope.resources.push(angular.copy(this));
$scope.name="";
$scope.description=""
}
Push the copy to the resources array and change name and description back to ""

Categories

Resources