I cannot seem to get my dropdown to default to having the first store selected.
html:
<select
id="store"
class="form-control input-inline input-medium"
ng-model="orderVm.Stores.selectedStore.id">
<option
ng-repeat="store in orderVm.Stores"
value="{{store.Id}}">
{{store.MarketplaceName}}
</option>
</select>
{{orderVm.Stores.selectedStore}}
vm.Stores (loaded from a local JSON file):
[
{
"Id": 1,
"MarketplaceId": 1,
"MarketplaceName": "Etsy"
]
},
{
"Id": 2,
"MarketplaceId": 2,
"MarketplaceName": "Shopify"
}
]
controller:
angular
.module('WizmoApp')
.controller('orderController', orderController);
orderController.$inject = ['$http', '$location', 'toastr', 'DTColumnDefBuilder', 'DTOptionsBuilder', 'Cart', 'OrderService', 'PackageService'];
function orderController($http, $location, toastr, DTColumnDefBuilder, DTOptionsBuilder, Cart, OrderService, PackageService) {
var vm = this;
vm.Stores = json; //from file
vm.Stores.selectedStore = {
id: vm.Stores[0].Id,
name: vm.Stores[0].MarketplaceName
};
OrderService.getOrdersGroupedByStore(function (json) {
vm.Stores = json;
vm.selectedStore = {};
});
routes.js:
.state('layout.orders', {
url: '/orders',
templateUrl: '/Content/js/apps/store/views/order.html',
controller: 'orderController',
controllerAs: 'orderVm',
data: { pageTitle: 'Orders' }
})
(It doesn't help that the first option is blank, but first things first.)
I'd use ng-options but frankly, it's even more obscure than this.
https://jsbin.com/kanaco/edit?html,js,output
I write a sample code for you.
Use ng-options for select.
edit:
<select id="store" class="form-control input-inline input-medium"
ng-model="ctrl.selectedStores"
ng-options="item.MarketplaceName for item in ctrl.Stores"
ng-init="ctrl.selectedStores=ctrl.Stores[0]">
</select>
You can use ng-options for repeat option, and use ng-init for default select.
Never use ng-repeat to build select options. Instead, use ng-options, which has a dedicated directive for this:
<select
id="store"
class="form-control input-inline input-medium"
ng-model="orderVm.Stores.selectedStore"
ng-options="store.ID as store.MarketplaceName for store in orderVm.Stores">
</select>
In your controller, you need to assign a default value to the select model:
orderVm.Stores.selectedStore = 1;
This would cause the Etsy option to be selected when the controller loads. Note that the model is just an id here, you don't need to use an object. The reason you were getting an empty option is that Angular could not bind the model to any of the options.
I had a very similar problem to yours and was asissted by a kind guru.
Related
I've a DropDownList where user has to select options and save it to database. I am using the following with AngularJs:
<select>
<option>----Please Select Sub-Category----</option>
<option ng-repeat="m in Categories" value="{{ m.CategoryId }}" ng-model="saveProducts.CategoryId">{{ m.Category }}</option>
</select>
I can show the values in the above DropDownList but stuck to retrieve the value from the selected and pass it to the scope. I've tried even this, a silly one:
<select>
<option>----Please Select Sub-Category----</option>
<option ng-repeat="m in Categories" value="{{ m.CategoryId }}" ng-model="m.CategoryId">{{ m.Category }}</option>
</select>
But that will not work. saveProducts is the object (scope) where I am passing values but is there any easy way where I can pass option value with the above procedure?
Here what I am doing to save data in database and it works fine except the option value, it's unable to retrieve values with the above:
productApp.controller('addProductController', function ($scope, $http) {
$scope.addData = function () {
$http({
method: 'POST',
url: '/Product/AddProductsToDb',
data: $scope.saveProducts
}).success(function () {
$scope.saveProducts = null;
}).error(function () {
alert('Failed');
});
}
});
This is the output I have and just want to pass the option value from it:
Update 1 - This is what I've tried but I can show the value in the alert method using as follows:
<select ng-model="saveProducts.ParentId"
ng-options="m.Category for m in Categories track by m.CategoryId">
<option value="">----Please Select Sub-Category----</option>
</select>
AngularJs Controller:
productApp.controller('addProductController', function ($scope, $http) {
$scope.addData = function () {
angular.forEach($scope.saveProducts, function (model, index) {
$scope.saveProducts.ParentId = (model.CategoryId);
});
alert($scope.saveProducts.ParentId);
$http({
method: 'POST',
url: '/Product/AddProductsToDb',
data: $scope.saveProducts
}).success(function () {
$scope.saveProducts = null;
}).error(function () {
alert('Failed');
});
}
});
Note: It saves TextBox input value but stuck with DropDownList. Unable to retrieve select option value and save it to database.
You should have a property to store the selected option. You can use ng-options to render the dropdown.
<select ng-model="selectedCategory"
ng-options="option.Category for option in Categories track by option.CategoryId ">
<option value="">Select Option</option>
</select>
Now your select element's ng-model is set to selectedCategory. So in your add method you can access that and use that for saving.
$scope.addData = function () {
console.log($scope.selectedCategory);
//to do : use selectedCategory
}
Use ngOptions. Depending on the structure of your Categories data, you could do something like:
<select ng-options="m as m.yourProperty for m in Categories" ng-model="selected"></select>
Then, in Angular...
$scope.selected = $scope.Categories[0];
Read the ngOptions documentation to tweak according to your needs.
This is my HTML
<select ng-model="selectedToggle" ng-change="changedValue()">
<option ng-repeat="x in toggle" value="{{x.data}}" ng-selected="">{{x.name}}</option>
</select>
This is my angularjs
var app = angular.module('myApp', []);
app.controller('namesCtrl', function($scope, $http) {
$scope.toggle = [
{data: "orderer", name: "Orderer"},
{data: "creator", name: "Creator"}
]
$scope.selectedToggle = $scope.toggle[1];
});
Im using the ng-repeat over ng-options is I want to put the data to value
This line $scope.selectedToggle = $scope.toggle[1]; will work only if I use ng-options is their any way to make a pre-selected while the value of <options> will have an orderer and creator
It should be like this
$scope.selectedToggle = $scope.toggle[1].data;
let me explain my scenario. I am having the dropdownlist in my master page. if changed dropdownlist the data are changed depend upon the dropdownlist value.
If i refreshed my page or moved to another page the dropdownlist will clear automatically.
I want to retain the dropdownlist value after refresh the page or moved to another page.
I tried like this but this is not help ful.
HTML
<select id="Facility_ID" required typeof="text" name="Facility Name" ng-options="Role.FacilityName for Role in Roles"
form="DistanceMatrixFormId" class="form-control" ng-model="Role._id" ng-selected="getFacilityID(Role._id.FacilityName)">
</select>
Controller.js
$scope.getFacilityID = function (data) {
localStorage.setItem("FacilityName", data);
var getfacility = localStorage.getItem("FacilityName");
}
i refered this link but it is not help ful
I don't know how to retain the value. can any one fixed me.
You cannot put an object into the local storage, you must store strings inside local storage.
If you want, you can have an implementation I did here : How to add local storage in angular?
For your current code, you don't need to use ng-selected. ng-model is enough.
<select id="Facility_ID" required typeof="text"
name="Facility Name"
ng-options="Role.FacilityName for Role in Roles"
form="DistanceMatrixFormId"
class="form-control"
ng-model="Role._id"
ng-change="updateLocalStorage()">
</select>
And inside your angular controller, what you can do is the following :
myApp.controller('controllerName', ['$scope', 'LocalStorageService',
function($scope, LocalStorageService){
// After initialization of your "Role" object
$scope.Role._id = LocalStorageService.retrieve('mySelectValue');
$scope.updateLocalStorage = function(){
LocalStorageService.store('mySelectValue', $scope.Role._id);
}
}])
Here is an example that uses a service to store the selected value. Unfortunately the embedded demo does not work because of the sandboxing, but works when served as an application.
angular.module(
"App", []
).factory("MyStorage", function() {
const key = "selected";
return {
getValue: function() {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : null;
},
setValue: function(value) {
localStorage.setItem(key, JSON.stringify(value));
}
};
}).controller("MyCtrl", function($scope, MyStorage) {
$scope.options = ["A", "B", "C"];
$scope.selected = MyStorage.getValue();
$scope.$watch("selected", newValue => {
MyStorage.setValue(newValue);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="App" ng-controller="MyCtrl">
<select ng-model="selected" ng-options="x for x in options">
</select>
</div>
I have 2 select lists:
<select class="input-large" ng-model="bu.box.categoryId" ng-change="getSubCats()">
<option ng-repeat="cat in cats" value="{{cat.id}}">{{cat.name}}</option>
</select>
<select class="input-large" ng-model="bu.box.subCategoryId">
<option ng-repeat="subcat in subCats" value="{{subcat.id}}">{{subcat.name}}</option>
</select>
The object bu, subcats is injected to my controller from resolve and exists before bindings is render and cats i get from local storage:
$stateProvider.state('box',
{
url: '/box-card/:id',
templateUrl: '/partials/main.module/contollers/box.html?v=' + global_app_version,
controller: 'BoxController as boxCtrl',
resolve: {
Box: function ($stateParams, httpService) {
return httpService.getBox({ boxid: $stateParams.id });
}
}
})
Controller variables initialization look like this:
function boxController($scope, localStorageService, httpService, $state, appData, uiGridConstants, $modal, helpersService, $stateParams, $sce, Box) {
$scope.bu = Box.data.bu;
$scope.cats = localStorageService.get("cats");
$scope.subCats = Box.data.currentSubCats;
............
var controllers = angular.module('app.controllers');
controllers.controller('BoxController', boxController);
The problem is, when the select lists is rendered, they not initialized correctly,
The first option is selected instead of relevant initialization by ng-model.
What happen here? Why is not working correctly?
I checked all variables in debug, all fine... Need help here.
Try to solve the problem with ng-selected.
<select class="input-large" ng-model="bu.box.categoryId" ng-init="cat = cats[0]" ng-change="getSubCats()">
<option ng-repeat="cat in cats" value="{{cat.id}}">{{cat.name}}</option>
</select>
<select class="input-large" ng-model="bu.box.subCategoryId" ng-init="subcat = subCats[0]">
<option ng-repeat="subcat in subCats" value="{{subcat.id}}">{{subcat.name}}</option>
</select>
I use in my project ng-init like ng-init="subcat = subCats[0]"
change the subCats[0] and cats[0] for your init values
Try using $scope.$apply() .
From the article:
If you write any code that uses Ajax without $http, or listens for
events without using Angular’s ng-* listeners, or sets a timeout
without $timeout, you should wrap your code in $scope.$apply
It looks like exactly your case. Box is updated in a background request and angular listeners do not know that it was updated.
UPD1
Also Just noticed that the problem could hide here
$scope.bu is initialized before $scope.cats so model actually tries to match a still empty list of options.
upd2
just noticed in the comment that ng-options binding was a bit off.
try using
<select ng-options="cat.name for cat.id in cats track by cat.id" class="input-large" ng-model="bu.box.categoryId" ng-change="getSubCats()">
I can successfuly bind an array to a select tag in angular using this syntax:-
var mainApp = angular.module('mainApp', []);
mainApp.controller('mainController', [
'$scope',
function ($scope) {
$scope.testArray = [{ text: '1st', value: 1 }, { text: '2nd', value: 2 }];
}]);
My HTML is like this:-
<select ng-model="testModel" ng-options="theTitle.text as theTitle.text for theTitle in testArray"></select>
However this creates an option list like this:-
<select ng-options="theTitle.text as theTitle.text for theTitle in testArray" ng-model="testModel" class="ng-pristine ng-valid">
<option value="?"></option>
<option value="0">1st</option>
<option value="1">2nd</option>
</select>
How do you bind the value property in the array to the option value attribute and why does it display the first option as a ?
Is there something else I need to put in my ng-options attribute?
in in html section:
<select ng-model="testModel" ng-options="theTitle.text for theTitle in testArray"></select>
in javascript section
var mainApp = angular.module('mainApp', []);
mainApp.controller('mainController', [
'$scope',
function ($scope) {
$scope.testArray = [{ text: '1st', value: 1 }, { text: '2nd', value: 2 }];
$scope.testModel = $scope.testArray[0];
}]);
The reason that ? Is showing is because your ngModel has not been initialized. In mainController, initialize testModel to '1st'. You will see that the ? goes away, and your drop down list is initialized to your first item
In ng-options, the format goes value as alias, so you need:
<select ng-model="testModel" ng-options="theTitle.value as theTitle.text for theTitle in testArray"></select>
The ? option is created because your model value does not exist as an option in the select, so the browser adds it to display the input as empty. To fix it you want to initialise the model to a valid value, something like: ng-init="testModel = testArray[0].value"