Display name instead ID modal dropdown in angularjs - angularjs

there is a dropdown of country and state when I select country of name I have to pass id of country but after click event it should pass id but display as name how can I make it please guide
<md-select name="state" id="state" placeholder="Select a state" md-no-asterisk="true"
ng-change="getCounties(state)" ng-model="state">
<md-option ng-repeat="item in state track by id"
value="{{item.id}}">
{{item.name}}
</md-option>
</md-select>
{{AddressState}} /* This should be name instead of value how can i display this ? */
<div class="clearfix" ng-click="edit()">
Edit</a></div>
controller.ts :
$scope.AddressState = state;

Don't use state as your ng-model since state is already your data source. Consider instead using an object to capture all user input, with state as a property. Your ng-model will capture the ID on user selection, which is what you want, and you can use that to get the state name.
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.userInput = {
state: {}
};
$scope.state = [{
"name": "Califoria",
"id": 1
}, {
"name": "Texas",
"id": 2
}]
$scope.getCounties = function() {
// $scope.userInput.state is updated autmatically with the ID
console.log($scope.userInput)
// the associated data can be found using
let state = $scope.state.find(s => s.id == $scope.userInput.state)
$scope.selectedState = state.name; // for display
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="userInput.state" ng-change="getCounties()">
<option ng-repeat="item in state" value="{{item.id}}">
{{item.name}}
</option>
</select>
<p> {{selectedState}} </p>
</div>

Related

Angularjs Select values are getting removed from ngModel after being added programmicatically

I am using Angularjs with select2. I have a multiselect box that gets populated based off the values selected in another dropdown. I use an click event on a button for fire a method that adds a list of ids to the ngModel object assigned to the multiselect box. I can see the values getting added properly after I trigger a change event on that form element because even after reading articles and changing the ngModel value to be a object and not an array, the values still aren't binding when I add them programmatically. After I trigger the change event on the form element, I am able to see some of the values but not all of them. Some of the values were removed. Below is my code.
addRecord.vm
<div class="col-sm-4">
<select ui-select2="{ allowClear: false, minimumResultsForSearch: 10, theme: bootstrap }"
name="recordTemplate" ng-model="addRecordCtrl.selectedTemplate">
<option class="selectPlaceholder" value="" disabled selected hidden>- Chose Record Template -</option>
<option ng-repeat="template in addRecordCtrl.recordTemplates" value="{{record.name}}">{{record.name}}</option>
</select>
</div>
<div class="col-sm-9">
<button id="addButton" class="btn btn-primary btn-lg" ng-click="addRecordCtrl.addRecords()" ng-disabled="addRecordCtrl.isLoading
|| addRecordCtrl.isEdit">Add</button>
</div>
<div class="col-lg-9 col-xs-9" id="recordContainer" name="recordContainer">
<select ui-select2="{ allowClear: false, minimumResultsForSearch: Infinity}"
name="records" id="records" class="medium"
multiple ng-model="addRecordCtrl.records.id"
ng-required="true" ng-cloak>
<option ng-repeat="record in addRecordCtrl.availableRecords | notInArray:addRecordCtrl.selectedRecordIds.ids:'recordId'"
value="{{record.recordId}}">{{record.name}}</option>
</select>
<input type="hidden" ng-model="addRecordCtrl.selectedRecordName" value="">
</div>
app.js
recordApp.controller('RecordController', ['$http', '$window', '$modal', '$log','$filter', '$timeout', function ($http, $window, $modal, $log, $filter, $timeout) {
var self = this;
self.availableRecords = [{
recordId: "1",
name: "Love and Happiness"
},{
recordId: "2",
name: "Feel the Burn"
},{
recordId: "3",
name: "Juicy Baby"
}];
self.recordTemplates = null;
self.selectedRecordIds = {};
self.addRecords = function () {
//add record ids from the selected records.
self.recordTemplates.recordId.forEach(function (id) {
self.selectedRecordIds.ids.push(id.recordId);
});
self.recordAdded = true;
};
}]);
//filter to filter out ids that have already been selected.
recordsApp.filter('notInArray', ['$filter', function($filter){
return function(list, arrayFilter, element){
if(arrayFilter){
return $filter("filter")(list, function(listItem){
for (var i = 0; i < arrayFilter.length; i++) {
if (arrayFilter[i][element] == listItem[element])
return false;
}
return true;
});
}
};
}]);
The reason some of my values were getting deleted from the selectedRecordIds array after adding them programmatically was because they are not in the availableRecords array. Once I made sure those values where in the availableRecords array all was well.

How to select Default option (india) in Angular js?

country names displaying using select box, select option coming from external json file. Based on selected country i am loading state json file into another select box,till every thing is ok, Now I need set Default selected country as INDIA, I tried bellow code.
html
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<select id="country" ng-init="state1 = options['IN']" style="width:250px;" class="" name="selectFranchise" ng-model="state1" ng-change="displayState(state1)">
<option ng-repeat="(key,country) in countries" value="{{key}}">{{country[0]}}</option>
</select>
</div>{{countries}}{{state1}}
<div>
<select id="state" ng-model="cities">
<option ng-repeat="(state,city) in states[state1]" value="{{city}}">{{city}}</option>
</select>
</div>
</div>
script
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.states = {
"IN":[
"Delhi",
"Goa",
"Gujarat",
"Himachal Pradesh",
]
};
$scope.countries = {
IN: ["India"],
ZA: ["South Africa"],
AT: ["Austria"]
}
$scope.lastName = "Doe";
});
jsfiddle
Add this in the controller after defining your $scope.countries
$scope.state1 = Object.keys($scope.countries)[0];
Remove ng-init from Html page.

AngularJs: Ng-model object and single model Together

I do not have enough English to describe it, but I think you will understand it from the codes.
Basically my problem is that ng-model = "" ng-options = "" does not come up with form data when used together.
<select class="form-control" name="car_id" ng-model="car_id" ng-options="I.car_brand_code as I.car_brand_name for I in CarList" ng-change="GetState()" >
<option value="">Select Car</option>
</select>
The selection box for the brands of these cars
<div class="form-group">
<label class="mtb10">Model Year</label>
<input type="text" name="modelYear" class="form-control" ng-model="data.modelYear" placeholder="Car Year...">
</div>
This is the other form objects. Where ng-model is a different data "data." I can get it. How can I get the value in the selection box.
I need to get the "car_id" value.
Try this :
On change of the dropdown options pass the selected value into the function as a param.
Use array.filter() method to fetch the model year for the selected car based on the car id.
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {
$scope.CarList = [
{
"car_brand_code": 1,
"car_brand_name": "Maruti",
"model_year": 1990
},
{
"car_brand_code": 2,
"car_brand_name": "Ford",
"model_year": 2005
}
];
$scope.GetState = function(carId) {
var selectedCar = $scope.CarList.filter(function(item) {
return item.car_brand_code == carId;
});
$scope.data = {
"modelYear" : selectedCar[0].model_year
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select class="form-control" name="car_id" ng-model="car_id" ng-options="I.car_brand_code as I.car_brand_name for I in CarList" ng-change="GetState(car_id)" >
<option value="">Select Car</option>
</select>
<div class="form-group">
<label class="mtb10">Model Year</label>
<input type="text" name="modelYear" class="form-control" ng-model="data.modelYear" placeholder="Car Year...">
</div>
</div>

Angular ngOptions track by object keys

I would like to create a select element with ngOptions – so far so good:
<select ng-options="currency for (code, currency) in currencies track by code"
ng-model="something.currency"></select>
Now I want to track the options by the object key (so the value of the ng-model should be the key and not the value of the object). Is this possible in some simple way and how?
Is it what you're looking for ?
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope', function($scope) {
$scope.currencies_old = [
{code: "USD", curr: "$"},
{code: "IND", curr: "INR"}
];
$scope.currencies = {"USD": "USDollars", "EUR": "Euro"};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="GreetingController">
<select ng-model="item" ng-options="key as value for (key , value) in currencies"></select>
Code: {{item}}
<br/> <br/>
<select ng-options="item as item.curr for item in currencies_old track by item.code" ng-model="item_old"></select>
Code: {{item_old.code}}
</div>

$state.go() is not refreshing in AngularJS?

How to reload nested state of different controller when changing selectbox content in AngularJS?
I have 2 select boxes 1.Category and 2.SubCategory
Based on the category and subcategory, Products will be displayed on the inner state
category and subcategory come under addproducts state
products come under .productsettings state inside the addproducts state
But my problem is when I select both category and subcategory the product will be displayed that means
$state.go('addproducts.productsettings');
will work,But after selecting both after that when i change only subcategory selectbox it won't reload product state
$state.go('addproducts.productsettings');
will not work that wont load in ProductSettingsController
This is my html code it contains two select boxes
<form>
<div class="form-group">
<label for="exampleSelect1"><b>Category</b></label>
<select ng-model="selectedCategory" class="form-control" id="categories" ng-init="selectedCategory = null"
ng-change="onCategoryChange(selectedCategory)">
<option value="">--Select--</option>
<option ng-repeat="(key,value) in categories | orderBy:'catName'| groupBy:'catName'">{{key}}</option>
</select>
</div>
</form>
<!-- ----------------------------------- -->
</div>
<div class="col-md-3">
<!-- ----------------------------------- -->
<form>
<div class="form-group">
<label for="exampleSelect1"><b>SubCategory</b></label>
<select class="form-control" id="subcategories" ng-model="selectedSubCategory" ng-disabled="!selectedCategory"
ng-options="categories.subCatName for categories in categories | filter: {catName:selectedCategory}" ng-change="getValue()">
<option value="">--Select--</option>
</select>
</div>
</form>
<!-- ----------------------------------- -->
</div>
This is my js code
var appshop = angular.module('appShop', [ 'ui.router', 'angular.filter' ]);
appshop.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/category');
$stateProvider.state('addproducts',
{
url : '/addproducts',
views :
{
'body' :
{
templateUrl : 'category/manageproduct.htm',
controller : 'AddProductController'
}
}
})
.state('addproducts.productsettings',
{
url : '/productsettings',
views :
{
'productsbody#addproducts' :
{
templateUrl : 'category/productsettings.htm',
controller : 'ProductsSettingsController'
}
}
})
});
//==========================================================
appshop.controller('AddProductController',AddProductController);
function AddProductController($scope, $http,$state)
{
$scope.onCategoryChange = function(category)
{
if (!category)
{
$scope.selectedSubCategory = undefined;
}
}
var categoryPromise = $http.get("../rest/mcategory");
categoryPromise.success(function(data, status, headers, config)
{
$scope.categories=data;
});
categoryPromise.error(function(data, status, headers, config)
{
alert("Error");
});
$scope.getValue=function()
{
$state.go('addproducts.productsettings');
}
}
//==========================================================
appshop.controller('ProductSettingsController',ProductSettingsController);
function ProductSettingsController($scope,$http,$state)
{
alert("Clicked")//I need to get alert here
}
That two select boxes are come under AddProductController
And products are comed under nested state of this AddProductController it is named as ProductSettingsController
When i select both category and subcategory it works fine
But after selcting both then only to changed subcategory it wont works
Any idea for getting product details when i select subcatname? I need to get alert Clicked in ProductSettingsController when i changed in subcategory selectbox
use $stateParams means parameters in url: look
HTML SubCategory section
<!-- ----------------------------------- -->
<form>
<div class="form-group">
<label for="exampleSelect1"><b>SubCategory</b></label>
<select class="form-control" id="subcategories" ng-model="selectedSubCategory" ng-disabled="!selectedCategory"
ng-options="categories.subCatName for categories in categories | filter: {catName:selectedCategory}" ng-change="getValue(selectedSubCategory)">
<option value="">--Select--</option>
</select>
</div>
</form>
<!-- ----------------------------------- -->
JS add stateParams in substate
.state('addproducts.productsettings',
{
url : '/productsettings?:subitem',
views :
{
'productsbody#addproducts' :
{
templateUrl : 'category/productsettings.htm',
controller : 'ProductsSettingsController'
}
}
})
Controller
$scope.getValue=function(sub_item)
{
$state.go('addproducts.productsettings', {subitem:sub_item});
}
try:
$state.reload();
or
$state.go('addproducts.productsettings', {}, {reload: true});

Resources