How to assign default value in Dropdownboxlist? - angularjs

Hi I am developing angularjs application. I tried many ways to set default value for dropdown in Angularjs but I am not able to set default value.
<select ng-change="getModel(b.ID)" ng-model="b.ID" id="brand" ng-options="b.MakeName for b in list">
<option value="1">-- Select a Make --</option>//Not working
</select>
<select ng-change="getStyle(a.ID)" ng-model="a.ID" ng-options="a.ModelName for a in Modellist" id="make" >
<option value="1">-- Select a Model --</option>
</select>//Not working
<select ng-change="getallDetails(c.ID)" id="type" ng-model="c.ID" ng-options="c.BodyStayleName for c in ModelStyle">
<option value="1">-- Select a Type --</option>
</select>//Not working
May I know am i missing here anything? Any help would be appreciated. Thank you.

Use ng-init or set the default value to the model variable inside the controller,
$scope.BrandId = "1";
DEMO
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script>
angular.module("myapp", [])
.controller("MyController", function($scope) {
$scope.register = {};
$scope.BrandId = "1";
$scope.brands = [{
id: "1",
name: "TOYOTA"
}, {
id: "2",
name: "HONDA"
}, {
id: "3",
name: "MARUTI"
}, {
id: "4",
name: "BMW"
}];
});
</script>
</head>
<body ng-app="myapp">
<div ng-controller="MyController">
<div>
<select ng-init="BrandId=='1'" ng-model="BrandId" ng-options="brand.id as brand.name for brand in brands"></select>
</div>
</div>
</body>
</html>

Related

How to set default select value in AngularJS?

I am totally new to Angular Js 1.0 and I am struggling in one of the simple code here. I wanted to show the default selected value in my dropdown. Below is the code I have used
<select id="ddlHeritage" class="form-control" columnname="HeritageIssues"
ng-change="riskCltr.showriskcomment()"
ng-focus-compliance="" ng-model-options="{'updateOn':'default blur', 'debounce':{'default': 250, 'blur':0}}" ng-model="McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues">
<option ng-repeat="item in (ValuerList = (McProMainCtrl.mcProEntry.McPro_DropDownData | orderBy:'Name' | filter:{GroupID:'120'} )) "
ng-selected="{{item.Value==McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues}}" value="{{::item.Value}}">
{{::item.Name}}
</option>
</select>
In the above code I am getting dropdown value from database(including the "--Select--" value)
However, I have null values under the field McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues.
I wanted to select value --Select-- when McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues value is null. I am actually struggling as to how to accomplish it in angularjs
When I add the below line above Option it add two "Select"
<option value="null">--Select--</option>
Any help is appreciated.
Try adding value="null" in your select element :
<select id="ddlHeritage" value="null" class="form-control" columnname="HeritageIssues"
ng-change="riskCltr.showriskcomment()"
ng-focus-compliance="" ng-model-options="{'updateOn':'default blur', 'debounce':{'default': 250, 'blur':0}}" ng-model="McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues">
<option ng-repeat="item in (ValuerList = (McProMainCtrl.mcProEntry.McPro_DropDownData | orderBy:'Name' | filter:{GroupID:'120'} )) "
ng-selected="{{item.Value==McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues}}" value="{{::item.Value}}">
{{::item.Name}}
</option>
</select>
This is similar things I have solve in my project. No need any option
var app = angular.module('angularjs-starter', []);
app.controller("unitController", function ($scope) {
$scope.units = [{name: "Crore", value: "Crore"},
{name: "Lakh", value: "Lakh"},
{name: "INR", value: "INR"},
{name: "--------", value: "", separator: true},
{name: "Million", value: "Million"}];
$scope.financialDataUnit = "Crore";
});
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller='unitController'>
<select ng-model="financialDataUnit"
ng-options="unit.value as unit.name disable when unit.separator for unit in units">
</select>
</body>
</html>

make JSON array from dynamic form data angular

i have a dynamic form in angular. and i want to send the response as json. how do i generate JSON from the form?
here's the complete code,I have to get json, and post it to some api.
<!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="dyf" ng-submit="submit()">
<form name="userFormOne" novalidate>
<table>
<tr class="form-group" ng-repeat="x in names">
<td><label>{{ x.Field }}</label>
</td><td><input type="text" class="form-control" placeholder="{{x.Comment}}" required>
</td>
</tr>
</table>{{data}}
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('dyf', function($scope, $http) {
$http.get("http://localhost:5000/gu")
.then(function (response) {$scope.names = response.data;console.log(response.data);});
$scope.data ={};
});
</script>
</body>
</html>
In AngularJs we use ng-model to bind inputs value to our controller, sample:
This full sample to figure out how to create a simple form, from array and how to send it as JSON to your API.
Note: On submit check your console, and see the objects value.
var app = angular.module("app", []);
app.controller("ctrl",
function ($scope) {
var options = [
{ name: "a" },
{ name: "b" },
{ name: "c" }
];
$scope.names = [
{ id: 1, field: "insert name", name: "name", placeholder: "your name is", value:null, type:"text" },
{ id: 2, field: "insert phone", name: "phone", placeholder: "your phone is", value: null, type: "tel" },
{ id: 3, field: "insert age", name: "age", placeholder: "your age is", value: null, type: "number", min: 0, max: 20 },
{ id: 4, field: "select country", name: "country", placeholder: "your country is", value: null, type: "select", options: options }
];
$scope.sendMe = function() {
console.log($scope.names);
}
});
<!DOCTYPE html>
<html ng-app="app" ng-controller="ctrl">
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<form name="userFormOne" novalidate>
<table>
<tr class="form-group" ng-repeat="x in names">
<td>
<label>{{ x.field }}</label>
</td>
<td ng-if="x.type != 'select'">
<input type="{{x.type}}" min="{{x.min}}" max="{{x.max}}" ng-model="x.value" name="{{x.name}}" placeholder="{{x.placeholder}}" ng-required="true">
{{x.value}}
</td>
<td ng-if="x.type == 'select'">
<select ng-model="x.value" name="{{x.name}}" ng-options="item as item.name for item in x.options">
</select>
{{x.value}}
</td>
</tr>
</table>
<button ng-disabled="userFormOne.$invalid" ng-click="sendMe()">sendMe</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>

Set Selectedvalue in dropdown in AngularJS

I am using AngularJS. I am trying to bind a dropdown with value shown from response. But I am not able to set the selected data. It always shows the default. Below is the index.cshtml:
<div class="col-sm-4">
<select name="CopyseasonTypeSelect" ng-model="CopyselectedSeasonType" ng-options="CopySeason.SeasonTypeName for CopySeason in seasons">
<option value="">-- Select the Season --</option>
</select>
</div>
In controller.js
testAPIService.getSeasonById(nId).success(function(response) {
$scope.seasonByIdReponse = response;
$scope.CopyselectedSeasonType = response.SeasonType; // I am getting "Summer"
$scope.init();
});
}
The dropdown has the values "-- Select the Season -- ", "Winter", "Summer", "Spring"
The object array is as below:
[object Object],[object Object],[object Object],[object Object]
[
0: {
[functions]: ,
$$hashKey: "object:78",
__proto__: { },
Id: 1,
ImageUrl: "testicon.png",
SeasonDetail: null,
SeasonTypeName: "Winter"
},
1: { },
2: { },
3: { },
length: 4
]
How to set the value in the dropdown from the service?
<select name="CopyseasonTypeSelect"
ng-model="CopyselectedSeasonType"
ng-options="i.SeasonTypeName as i.SeasonTypeName for i in seasons">
<option value="" style="display: none">-- Select the Season --</option>
</select>
Try this. Use track by in the ng-options to initialize it
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div class="container">
<select name="CopyseasonTypeSelect" ng-model="CopyselectedSeasonType" ng-options="CopySeason.SeasonTypeName for CopySeason in seasons track by CopySeason.Id">
<option value="">-- Select the Season --</option>
</select>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.seasons = [{
SeasonTypeName: "Winter",
Id: 0
},
{
SeasonTypeName: "Summer",
Id: 1
},
{
SeasonTypeName: "Spring",
Id: 2
}];
$scope.CopyselectedSeasonType = $scope.seasons[1];
});
</script>
</body>
</html>

How to set default value in each cascading dropdown using angular?

I have the dropdown as demonstrated below. All of this work. I just need to set default value for each one. I know how to do it for the upper level but how to do it for the next levels?
This is my html code:
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.20/angular.js" data-semver="1.2.20"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div class="row">
<div class="col-md-4 col-xs-4 col-sm-4">
<select required ng-change="onBookChange(books,book)" ng-model="book" ng-options="bb.bookName for bb in books" class="form-control" >
<option value="">--Select--</option>
</select>
</div>
<div class="col-md-4 col-xs-4 col-sm-4">
<select required ng-model="chapter" ng-change="onChapterChange(books,chapter)" ng-options="cha.chapterName for cha in books.selectedChapters" class="form-control" >
<option value="">--Select--</option>
</select>
</div>
<div class="col-md-4 col-xs-4 col-sm-4">
<select required ng-model="title" ng-change="onTitleChange(books,title)" ng-options="t for t in books.selectedTitles" class="form-control" >
<option value="">--Select--</option>
</select>
</div>
</div>
</body>
</html>
and this is my javascript code:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.books=[
{
id:1,
bookName:'C++',
chapter:[
{chapterName:'Introduction',titles:['About Author','C++ Basic']},
{chapterName:'OOPS basic',titles:['Class','Object','Data Encapsulation','Inheritance','Interface']},
]
},
{
id:2,
bookName:'Java',
chapter:[
{chapterName:'Java Introduction',titles:['About Author','Java Intro']},
{chapterName:'Java basic',titles:['Variables','Function','Function Overloading','Class','Object']},
]
},
{
id:3,
bookName:'Angular JS',
chapter:[
{chapterName:'Introduction',titles:['MVC','Model','View','Controller']},
{chapterName:'Key Features',titles:['Template','Scope','Expressions','Filter','Controller','Module']},
]
}
];
$scope.onBookChange=function(b,book){
//alert("inside");
b.selectedChapters=book.chapter;
}
$scope.onChapterChange=function(b,cha){
//alert("inside");
// console.log(cha);
b.selectedChapter=cha;
b.selectedTitles=cha.titles;
}
$scope.onTitleChange=function(b,t){
// alert(t);
b.selectedTitle=t;
}
});
Please see demo below
var app = angular.module('app', ['ui.bootstrap']);
app.controller('homeCtrl', function($scope) {
$scope.books = [
{
id: 1,
bookName: 'C++',
chapter: [{
chapterName: 'Introduction',
titles: ['About Author', 'C++ Basic']
}, {
chapterName: 'OOPS basic',
titles: ['Class', 'Object', 'Data Encapsulation', 'Inheritance', 'Interface']
},
]
}, {
id: 2,
bookName: 'Java',
chapter: [{
chapterName: 'Java Introduction',
titles: ['About Author', 'Java Intro']
}, {
chapterName: 'Java basic',
titles: ['Variables', 'Function', 'Function Overloading', 'Class', 'Object']
},
]
}, {
id: 3,
bookName: 'Angular JS',
chapter: [{
chapterName: 'Introduction',
titles: ['MVC', 'Model', 'View', 'Controller']
}, {
chapterName: 'Key Features',
titles: ['Template', 'Scope', 'Expressions', 'Filter', 'Controller', 'Module']
},
]
}
];
$scope.onBookChange = function(b, book) {
//set default chapter
$scope.chapter = book.chapter[0];
//set default title
$scope.title = $scope.chapter.titles[0];
}
$scope.onChapterChange = function(b, chapter) {
$scope.title = chapter.titles[0];
}
$scope.onTitleChange = function(b, t) {
// alert(t);
b.selectedTitle = t;
}
});
<head>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap-tpls.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div ng-app="app">
<div ng-controller="homeCtrl">
<div class="row">
<div class="col-md-4 col-xs-4 col-sm-4">
<select required ng-change="onBookChange(books,book)" ng-model="book" ng-options="bb.bookName for bb in books" class="form-control">
<option value="">--Select--</option>
</select>
</div>
<div class="col-md-4 col-xs-4 col-sm-4">
<select required ng-model="chapter" ng-change="onChapterChange(books,chapter)" ng-options="cha.chapterName for cha in book.chapter" class="form-control">
<option value="">--Select--</option>
</select>
</div>
<div class="col-md-4 col-xs-4 col-sm-4">
<select required ng-model="title" ng-change="onTitleChange(books,title)" ng-options="t for t in chapter.titles" class="form-control">
<option value="">--Select--</option>
</select>
</div>
</div>
</div>
</div>
</body>
you have your ng-models set to book, chapter, title. You just need to assign the default values to these on the scope
$scope.book = $scope.books[0];
//in the onBookChange function
$scope.chapter = book.chapter;
//in the onChapterChange function
$scope.title = cha.titles[0];

ng-show when array length is zero

I am a beginner for AngularJS. I am trying to display "No Tag Found" during filter process with the help of "ng-show".
JS:
function simpleController($scope)
{
$scope.tags = ['HTML','CSS','Jquery','Bootstrap','AngularJS'];
}
HTML:
<div ng-controller="simpleController">
<input class="txt" type="text" ng-model="nameText" />
<div>
<ul>
<li ng-repeat="myKeys in tags| filter:nameText">{{myKeys}}</li>
</ul>
<div ng-show="!tags.length">No Tag Found</div>
</div>
</div>
When I type any value other than array vales, I am not able to get "No Tag Found" using the above code. Please help. Thanks.
If you're filtering in your ng-repeat, you must apply the same filter for you ng-show. If you don't, the ng-show will always refer to the full array :
<div ng-show="!(tags| filter:nameText).length">No Tag Found</div>
Working fiddle : http://jsfiddle.net/HB7LU/3149/
Just better use ng-hide:
<div ng-hide="tags.length">No Tag Found</div>
<div class="box" ng-show="team_stores.length > 0" >
worked for me
easy way to create filter... demo is as below
var app = angular.module('myApp', []);
app.controller('myctrl', function ($scope) {
$scope.friends = [
{ name: "Peter", age: 20 },
{ name: "Pablo", age: 55 },
{ name: "Linda", age: 20 },
{ name: "Marta", age: 37 },
{ name: "Othello", age: 20 },
{ name: "Markus", age: 32 }
];
});
<!DOCTYPE html>
<html>
<head>
<title>welcome</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myctrl">
Name: <input ng-model="filter" type="text" />
<ul>
<li ng-repeat="friend in friends |filter:filter">{{friend.name}}</li>
<li ng-show="!(friends| filter:filter).length">data not found</li>
<!--<link ng-repeat="friend in friends|filter:isActive ">-->
</ul>
</body>
</html>
Also you can try to use filter service, like this: $filter('filter')(array, expression, comparator), this service return new array.
you can see http://code.angularjs.org/1.2.16/docs/api/ng/filter/filter

Resources