Angular Default Value in Server Supplied Dropdownlist - javascript

I have a dropdownlist of U.S. States which is populated from a call to our web api. I have an edit page that fills in a user's details and I need to bind that dropdownlist to the state in the user's information. I'm sure this has something to do with ng-options, but I do not know how to implement it.
Here is my HTML for the dropdownlist:
<select data-ng-model="form.vchOfficeStateVchID" ng-options="s as s.StateVchID for s in userdetails.vchOfficeStateVchID" style="height:25px">
<option value="">--Select State--</option>
<option ng-repeat="state in states" value="state.StateVchID">{{state.StateVchID}}</option>
</select>
The function in my controller that populates the dropdownlist is:
getStates();
function getStates() {
operatorService.getallstates()
.success(function (data) {
$scope.states = data;
});
};
It returns an array which has the state abbreviation as its key "StateVchID" (I didn't create this database).
The user info is returned in the controller with the following function:
$scope.showDetails = function (user) {
$scope.noUser = false;
var userid = user.UserID;
operatorService.getuserdetails(userid)
.success(function (data) {
$scope.userdetails = data;
$scope.form.vchOfficeStateVchID = userdetails.vchOfficeStateVchID;
$scope.form.vchOfficeCountryVchID = userdetails.vchOfficeCountryVchID;
});
$scope.viewUser = true;
};
In the user's details, the State Abbreviation is held in the vchOfficeStateVchID field.
How do I get my dropdownlist to display the user's correct state? Basically, I need state.StateVchID = userdetails.vchOfficeStateVchID.
Any assistance is greatly appreciated!

Have a look at this example:
HTML
<div ng-app="myApp" ng-controller="myController">
<select name="vchOfficeStateVchID" ng-model="form.vchOfficeStateVchID" ng-options="s.StateVchID as s.Name for s in states">
<option value="">--Select State--</option>
</select>
<br/>
<div>
<h3>
Selected ID:
</h3>
{{form.vchOfficeStateVchID}}
</div>
</div>
JavaScript
var app = angular.module("myApp", []);
app.controller("myController", ["$scope", function($scope){
$scope.userdetails = {
vchOfficeStateVchID: 3
}
$scope.form = {};
$scope.states = [
{
Name: "New York",
StateVchID: 1
},
{
Name: "Texas",
StateVchID: 2
},
{
Name: "Las Vegas",
StateVchID: 3
},
{
Name: "Hawaii",
StateVchID: 4
}
];
$scope.form.vchOfficeStateVchID = $scope.userdetails.vchOfficeStateVchID;
}]);

Related

Default value in Select field

I am confused about why I am getting this specific malfunction, I am unable to get a default value for my select dropdown list. My goal is to have "Choose Board" as the default but despite many trials, I have been unable to get this as the default value.
I have attempted a variety of solutions: AngularJS - Set default value on select inside a ng-repeat & How to have a default option in Angular.js select box
Without any luck.
My HTML Tags:
<select name="boardInput" class="form-control"
ng-required="true"
ng-init="form.boardInput = boards[0]"
ng-model="form.boardInput"
ng-options="board.name for board in boards">
</select>
My JS controller code
//TRELLO CONTROLLER
$scope.baseBoards =[{
id: false,
name: "Choose Board"
}];
$scope.getBoards = function() {
trello.getBoards('me', function(error, boards){
if(error){
log("Could Not Get Boards: ", error);
} else {
log("found " + boards.length + " boards");
$scope.boards = $scope.baseBoards.concat(boards);
}
});
};
The result is a field being added and set as the default, in the above code the null field disappears after any of the others are selected.
any help is much appreciated.
Try
<select name="boardInput" class="form-control"
ng-required="true"
ng-model="form.boardInput"
ng-options="board.name for board in boards">
</select>
and in your Controller
$scope.form.boardInput = "Choose Board"
If it works then you can replace the text with your desired variable such as $scope.baseBoards[0].name.
Please check this updated answer. For now your trello.getBoards I have commented, once you add it in your code, uncomment it and comment var boards this variable.
var app = angular.module('app', []);
app.controller('myController', ['$scope', function($scope) {
$scope.boards = [];
$scope.baseBoards = [{
id: false,
name: "Choose Board"
}];
$scope.getBoards = function() {
/* trello.getBoards('me', function(error, boards) {
if (error) {
log("Could Not Get Boards: ", error);
} else {
log("found " + boards.length + " boards");
$scope.boards = $scope.baseBoards.concat(boards);
}
}); */
//You will get boards data from your trello.getBoards method but I dont have access it so declaring local variable.
var boards = [{
name: 'one'
}, {
name: 'two'
}, {
name: 'three'
}]
$scope.boards = $scope.baseBoards.concat(boards);
};
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app='app' ng-controller='myController' ng-init="getBoards()">
<select name="boardInput" class="form-control" ng-required="true" ng-init="form.boardInput = boards[0]" ng-model="form.boardInput" ng-options="board.name for board in boards">
</select>
</div>

How to assign a second parameter value on ng-change in angularjs?

I have simple drop-down bind with angular model
<select
ng-model="user.Id"
ng-options="convertToInt(c.Id) as c.Name for c in users"
ng-change="changeItem(user.Id)"
>
<option ng-selected="c.Id == user.Id" value="{{c.Name}}"></option>
</select>
and in controller
$scope.changeItem = function(item){
//userid
}
How can I get User name from the select box, ie return c.Name?
Pass the Alice object
ng-change="changeItem(c)"
and then,
$scope.changeItem = function(user){
console.log(user.name);
}
Pass the whole user object
ng-change="changeItem(c)"
and then,
$scope.changeItem = function(item){
console.log(item.name);
}
What about
<selectng-model="user"
ng-options="item as item.name for item in users track by item.id"
ng-change="onChange()">
</select>
$scope.onChange = function(){
console.log($scope.user);
};
Working demo
Select the entire object to a selectedUser and you can get what ever you want out of the object.
<div ng-app="myApp" ng-controller="HomeCtrl as vm">
<select ng-options="user as user.name for user in vm.users" ng-model="vm.selectedUser"></select>
<p>Selected user: {{vm.selectedUser.name}}</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
angular.module('myApp', [])
.controller('HomeCtrl', function() {
let vm = this;
vm.users = [
{
id: 1,
name: 'John',
},
{
id: 2,
name: 'Joe',
},
{
id: 3,
name: 'Jim',
},
];
vm.userId = 2;
vm.selectedUser = vm.users.find(u => u.id === vm.userId);
});
</script>

Angular - how to initialize default value on select2

I use select2 in my Angular project , Actually I have a problem that is I have no idea about how to set default value for select-option. Here is my code :
HTML :
<select-tag-manager parent-id="2" value="restaurant.type" ></select-tag-manager>
Angular :
app.directive('selectTagManager', function() {
return {
restrict: "E",
replace: true,
scope: {
parentId: '#',
value: '='
},
controller: function($rootScope, $scope, Gateway, toaster, $element, Tags) {
var element;
$scope.update = function () {
};
var makeStandardValue = function(value) {
var result = [];
angular.forEach(value , function(tag , key) {
if(result.indexOf(tag.tagId) < 0) {
result.push(tag.tagId);
}
});
return result;
};
var init = function () {
Gateway.get('', '/tag?' + 'parentId=' + $scope.parentId, function(response) {
$scope.allPossibleTags = response.data.result.tags;
});
element = $($element).children().find('select').select2();
console.log(element);
};
$scope.$watch('value', function(newval) {
if( newval ) {
$scope.standardValue = [];
angular.forEach(newval, function(val, key) {
$scope.standardValue.push(val.tagName);
});
console.log($scope.standardValue);
}
});
init();
},
templateUrl: 'selectTagManager.html'
}
});
selectTagManager.html:
<div class="row">
<div class="col-md-12">
{{ standardValue }}
<select class="select2" multiple="multiple" ng-model="standardValue" ng-change="update()">
<option ng-if="tag.tagId" ng-repeat="tag in allPossibleTags" data-id="{{tag.tagId}}" value="{{tag.tagId}}">{{ tag.tagName }}</option>
</select>
</div>
</div>
I got value
console.log($scope.standardValue);
result: ["lazzania", "pizza", "kebab"]
But I don't know how to set them as default value in select-option. Any suggestion?
EDITED :
I've just edited my question using Angular-ui/ui-select2. I changed my template :
<select ui-select2 = "{ allowClear : true }" ng-model="standardValue" multiple="multiple" >
<option value="standardId" ></option>
<option ng-repeat="tag in allPossibleTags" value="{{tag.tagId}}">{{tag.tagName}}</option>
</select>
And also my js:
$scope.$watch('value', function(newval) {
if( newval ) {
$scope.standardValue = [];
$scope.standardId = [];
// $scope.standardValue = makeStandardValue(newval);
console.log('----------------------------------------------------------------------');
angular.forEach(newval, function(val, key) {
$scope.standardValue.push(val.tagName);
$scope.standardId.push(val.tagId);
});
console.log($scope.standardValue);
console.log($scope.standardId);
}
});
Nevertheless , Still I can't set default value.
as demonstarted at http://select2.github.io/examples.html#programmatic, one can set default values for multiple select2 element as follows:
$exampleMulti.val(["CA", "AL"]).trigger("change");
so, in you case you have already element variable pointing to your select2:
element.val($scope.standardValue).trigger('change');
note, that this is jQuery approach of setting/changing values, angular approach would be to update values via ng model and its life cycle events
The IDs in your model need to match the IDs in your data source, so if your model is:
["lazzania", "pizza", "kebab"]
Then allPossibleTags needs to look like:
[{ tagId: "lazzania", tagName: "Lazzania" }, { tagId: "pizza" ...
Check out this plunk for a working example:
http://plnkr.co/edit/e4kJgrc69u6d3y2CbECp?p=preview

Select using ng-option is not updating model in controller

I have the following array:
[{
"Id": 3,
"Name": "A"
},
{
"Id": 3,
"Name": "B"
},
{
"Id": 3,
"Name": "C"
}]
I am using this in the following Angular view:
<select ng-model="selectedCategory" ng-options="category.Name for category in categories"></select>
<pre>{{selectedCategory | json}}</pre>
<button type="button" ng-click="move()">Move</button>
The controller looks like:
var moveCategoryController = function ($scope, category, categoriesService) {
var getCategories = function () {
categoriesService.getCategories()
.success(function (result) {
$scope.categories = [];
for (var i = 0; i < result.Results.length; i++) {
var cat = result.Results[i];
if (cat.Id !== category.Id) {
$scope.categories.push(cat);
}
}
$scope.selectedCategory = $scope.categories[0];
})
.error(function () {
$scope.errorMessage = "There was a problem loading the categories.";
});
};
getCategories();
$scope.move = function () {
alert($scope.selectedCategory.Name);
};
}
bpApp.controller("moveCategoryController", moveCategoryController);
For info, the category object injected into the controller is a category object (the controller is being used in a modal and the category is passed to it from the parent page).
The Problem
On loading, the select is bound to the data fine, and when the user changes the select list the <pre> content updates correctly with the newly selected category.
The problem is when I click the Move button, which calls the move() function on the controller scope, the selectedCategory property of the scope has not been updated. For example, if I select the category "B", the alert still pops up with "A".
So, it seems that the ng-model is updated in the view, but not in the controller?!

Angular $http POST unable to bind array

So I'm trying to set up a post function using Angular. I've got a HTML form which has two text boxes (for user input) and a drop down menu for selecting a number of choices (so the user fills out the form and submits data to server).
Binding the two text boxes is fine but I don't know how to bind the two options in my array as choices in the drop down menu?
(Heres a fiddle:http://jsfiddle.net/gtv7s8h3/2/ )
Form:
<form>
<input type="text" id="name" ng-model="myForm.Title" ng-minlength="5" ng-maxlength="20"> title <br/>
<input type="text" id="name" ng-model="myForm.Content" ng-minlength="5" ng-maxlength="20"> content <br />
<select ng-model="CategoryId" ng-options="item.name for item in CategoryId"></select>
<button ng-click="myForm.submitTheForm()">Submit Form</button>
</form>
Angular POST:
angular.module("myapp", [])
.controller("MyController", function($scope, $http) {
$scope.myForm = {};
$scope.myForm.Title = "";
$scope.myForm.Content = "";
$scope.CategoryId = {
data: [{
id: '316556404cac4a6bb47dd4c7ca2dac4a',
name: 'name1'
}, {
id: '306e3d9a6265480d94d0d50e144435f9',
name: 'name2'
}]
};
$scope.myForm.submitTheForm = function(item, event) {
var dataObject = {
Title : $scope.myForm.Title,
Content : $scope.myForm.Content,
CategoryId : $scope.CategoryId
};
var responsePromise = $http.post("/url", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config) {
console.log(dataFromServer.title);
});
responsePromise.error(function(data, status, headers, config) {
alert("Submitting form failed!");
});
}
});
You're trying to bind the categoryID to you array and your ngOptions expression does not loop through your array. You need to bind the categoryId value to a different model.
Add a model for your categoryID:
$scope.myForm.categoryId = null;
and change your select markup:
<select ng-model="myForm.categoryId" ng-options="item.id as item.name for item in CategoryId.data"></select>

Categories

Resources