ng-model for select with defined options - javascript

I've got a plain select control in my angular app. When page loads I've got no element selected in select control but if I check $scope.data.Method I've got a correct value in int. Is there any way to fix this issue?
<div class="form-group">
<label class="col-sm-3 control-label">Selected Method:</label>
<div class="col-sm-4">
<select class="form-control" ng-model="data.Method">
<option value="0">Auction</option>
<option value="1">Delivery</option>
<option value="2">Range Delivery</option>
<option value="3">Broadcast</option>
<option value="4">Self broadcast</option>
<option value="5">Manual</option>
<option value="6">Automated</option>
</select>
</div>
</div>
Controlers use service to get data. Here is service code for getting data
//Initialize Resource
this.initResource = function (params) {
params = params || {};
params.id = '#id';
this.resource = $resource('{0}/:id'.format(this.api), params, {
'update': { method: 'POST' },
'create': { method: 'PUT' },
'default': { method: 'GET', params: { id: 'default' } }
});
}
//...more code
//Get some data and initialize additional parameters
this.read = function (id, clone, readonly, version) {
if (clone == undefined)
clone = false;
if (readonly == undefined)
readonly = false;
if (this.resource == null) {
this.initResourceByDefault();
}
return this.resource.get({ id: id, clone: clone, readonly: readonly, version: version });
}
Controller code
function ItemController($scope, $route, $routeParams, $location, $resource, MainCRUDService, ControllerHelper) {
$scope.noticeType = $routeParams.noticeType;
MainCRUDService.initResource({ noticeType: $scope.noticeType });
//Here I am getting data from resourse via service
ControllerHelper.initCRUD($scope, MainCRUDService);
}

As I can understand your problem, your service is returning data.Method as an integer value.
But select box will match a string value.
Your problem will get solved if your service will return data.Method as string. Also you can convert your response paramter data.Method to a string value, by using toString() method.
Here is a plunker code which may help you.
https://plnkr.co/edit/s0Wrk4?p=preview

Related

Unable to get selected value of dropdown in angular controller on its change event

I tried all of the way I found but it's not working, I am just simply trying to get selected option of a dropdown on its change event in angular js way so that it would be passed to the ajax and fetch the data from database. I have angular.min.js 1.4.8 version cdn in my project.
I copy/paste my code into plunker there its working fine but while running my project in browser its not working. Below is my JS and html code snippet.
JS Code
$scope.inputs = [{
id : 1,
name : 'option1',
value : 'option1',
inputType : 'tag',
valueOperator : "option1Operator",
operatorType : 'operatorType1'
}, {
id : 2,
name : 'option2',
value : 'option2',
inputType : 'text',
valueOperator : "option2Operator",
operatorType : 'operatorType1'
}];
$scope.inputSelectedChange = function(){
$scope.$watch('inputSelected',function( val ){
$http({
method: 'GET',
url: '<<URL>>',
responseType: 'json',
params:{inputName: "prdSeqId"}
}).then(function successCallback(response) {
//something
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
});
HTML Code
<select ng-model="inputSelected"
ng-options="input as input.name for input in inputs"
ng-change="inputSelectedChange()" required>
<option value="">Select Input</option>
</select>
//html
<select ng-model="inputSelected" id="inputSelected" class="form-control positionTypes" ng-options="input as input.name for input in inputs" ng-change="inputSelectedChange(inputSelected)" required>
<option value="">Select Input</option>
</select>
//controller
$scope.inputSelectedChange = function(value){
console.log(value)
};
try changing function like below:
and get value.
$scope.inputSelectedChange = function(){
console.log($scope.inputSelected)
//do other stuff here
}
You can get the value of selected item inside ng-change from ng-model
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.inputs = [{
id : 1,
name : 'option1',
value : 'option1',
inputType : 'tag',
valueOperator : "option1Operator",
operatorType : 'operatorType1'
}, {
id : 2,
name : 'option2',
value : 'option2',
inputType : 'text',
valueOperator : "option2Operator",
operatorType : 'operatorType1'
}];
$scope.inputSelectedChange = function(){
console.log($scope.inputSelected)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select ng-model="inputSelected" id="inputSelected" class="form-control positionTypes" ng-options="input as input.name for input in inputs" ng-change="inputSelectedChange()" required>
<option value="">Select Input</option>
</select>
</div>

How to get Select2 to update a ajax call when country value is changed

I can't seem to find an easy example of how to update the states list when the country list has changed. All examples I've seen to be using all sorts of bits and peices that work depending on version and who is giving the solution.
Can someone help me how this can be easily done without ugly hacks. I've tried this so far and whilst it works, if I change the drop down for the second time, the new values just get appended to the old ones instead of replacing them. I've tried destroying and rebuilding but old values remain.
The data coming back from the server is valid json with id and text values. So far I've had no luck in getting the state list to update with new country state values when the country is changed
<select id="country" name="country" class="form-control" data-placeholder="Select...">
<optgroup label="Country">
<option></option>
<option value="US" > United States</option>
<option value="AU" > Austrailia</option>
</optgroup>
</select>
<select id="state" name="state" class="form-control" data-placeholder="Select...">
<optgroup label="State">
<option></option>
</optgroup>
</select>
$("#country").select2().on("change", function(e) {
var country = e.val;
$.post("states", {
country_id: country
}, function(e) {
if (e)
$("#states").select2({
data: e
});
})
});
$("#state").select2();
These are the values sent back from server
[{ id: 'ALB', text: 'ALABAMA' }, { id: 'ALS', text: 'ALASKA' }, { id: 'ARI', text: 'ARIZONA' }]
You have to remove the <option> tags from the select before setting the new data:
$.post("states", {
country_id: country
}, function(e) {
if (e){
$("#states option").remove();
$("#states").select2({
data: e
});
}
})
You may want to refine my example to avoid removing placeholders, if any.
See also this JSFiddle: https://jsfiddle.net/drj84go5/
The best option is to have an input (text) not a select2 and then convert it through select2 function using ajax.
Input:
<input type="text" id="states">
Javascript:
$('#states').select2({
placeholder: "States...", // placeholder
allowClear: true,
minimumInputLength: 0,
dropdownCssClass: "bigdrop",
width: '100%',
ajax: {
quietMillis: 2500,
url: "/Search/_SearchStates", // Server-side action
dataType: 'json',
data: function (term, page) {
return {
Text: term, // Text to search for
CountryId: $("#country").val(), // CountryId from #countries
};
},
results: function (data, page) {
return { results: data };
},
},
formatResult: function (item) {
return item.StateName; // Table name/description
},
id: function (element) {
return element.StateId; // Table id/code
},
formatSelection: function (item) {
return item.StateName; // Table name/description
}
});
You need to have a server-side action that will give you the list of states.
To get the StateId you need to do:
$("#states").select2('val');

Parameter is not recognised by the function in .then angularjs

What I am trying to achieve is a dropdown list that produces lisof Metacategories. Once the user selects the meta category, the parameter should be passed onto the URI of the function present in $scope.meta().then(...). however, the parameter I am passing is category; ng-model="category". This parameter is not sent to the URI, I am getting an error:
TypeError: Cannot read property 'category' of undefined
HTML:
</select></center >
<center> <select ng-model="category" > <!-- This produces drop down list from which the users selects a category which should then get passed to the meta1() function as a parameter to produce a further list for the drop down after that-->
<option size=50 value="" selected>Select a meta category</option>
<option ng-repeat="meta in metas.metas" value="{{meta}}">{{meta}} </option>
</select></center>
<center> <select ng-model="category" >
<option size=50 value="" disabled selected>Select a category</option>
<option ng-repeat="category in categories.categories" value="{{category}}">{{category}} </option>
</select></center>
Angular:
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/post', {
templateUrl: 'templates/post.html',
controller: 'PostCtrl'
})
}])
.controller('UserListCtrl', function ($scope, $http) {
$scope.list = function () { // this gets the list of places which works completely fine.
$http.get('http://94.125.132.253:8001/getuncategorisedplaces').success(function (data) {
$scope.places = data;
console.log(data);
$scope.message = 'List of Uncategorised places';
$scope.meta = function () { // this gets list of meta categories, which is working fine.
return $http.get('http://94.125.132.253:8000/getmetas').success(function (data) {
$scope.metas = data;
console.log(data);
$scope.message = 'List of Uncategorised places';
})
}
// the function below should get a parameter category from previous function which is selected in HTML. Once this happens, the parameter category should be passed on as formdata.category(below) which will get the list of categories.
$scope.meta().then(function (data) {
var formdata = {
'category': this.category,
}
var inserturl = 'http://94.125.132.253:8000/getcategories?meta=' + formdata.category;
$http.get(inserturl).success(function (data) {
$scope.categories = data;
console.log(formdata.category);
console.log(data);
$scope.message = 'List of Uncategorised places';
});
});
})
}
$scope.list();
I would think that the error is caused by this:
$scope.meta().then(function meta1($scope,$http) {
because the meta method is not returning a promise.
The meta method could return a promise if you did this:
$scope.meta= function(){
return $http.get('http://94.125.132.253:8000/getmetas').success(function (data) {
$scope.metas = data;
console.log(data);
$scope.message = 'List of Uncategorised places';
return data;
});
};
and you could change the call to meta to this
$scope.meta().then(function(data) {
...
}
Missing return.
$scope.meta should return a promise for you to be able to use .then()
$scope.meta= function(){
return $http.get('http://94.125.132.253:8000/getmetas').success(function(...
...
}
$scope.meta().then(function (data) {
// do something with data
});

Angularjs populating dropdown with in ng-repeat from different scope

Hi I have following controller which gets data from database using factory which works fine.
My service is
App.factory("pOvRepository", ['$resource', function ($resource) {
return {
pw: $resource('/api/pOv/:id', { id: '#id' }, { update: { method: 'PUT' } }),
ps: $resource('/api/pStatus/:id', { id: '#id' }, { update: { method: 'PUT' } })
};
}]);
Controller is
App.controller('pOvCtrl', function ($scope, pOvRepository, $location) {
$scope.poviews = pOvRepository.pw.query();
$scope.pS = pOvRepository.ps.query();
The data I get for $scope.pS is
[{"p_status1":"Up Coming","p_id":1,"proj":[]},
{"p_status1":"In Progress","p_id":2,"proj":[]},
{"p_status1":"On Hold","p_id":3,"proj":[]}]
In my html code I am trying to populate the dropdown with data from $scope.pS
<div ng-controller="pOvCtrl">
<form ng-repeat="p in poviews">
<input type="text" ng-model="p.include_in"/>
<select ng-model="p.p_id" ng-options="a.p_status1 as a.p_id for a in pS"></select>
</form>
When I run it, the dropdown does not get populated with the options from $scope.pS
Please let me know how I can fix it.
Thanks
Hard to tell without seeing your service, you need to specify a callback for the data:
pOvRepository.ps.query({}, function(data) {
$scope.pS = data;
});

ASP.NET MVC Cascading DropDownLists Javascript Issues

After reviewing many tutorials and various approaches to Cascading DropDownLists, I decided to create a ViewModel for my View and then populate my DropDownLists based on this post:
MVC3 AJAX Cascading DropDownLists
The goal here is the most basic and covered in many tutorials, but I still can't get it quite right... to populate a City dropdown based on the value of a State dropdown.
EDIT:
Since posting this request for help, I discovered Firebug (yes, that's how new I am to doing any sort of programming), and I was able to determine that I am successfully calling my controller, and pulling the necessary data. I believe the problem is the second half of my JavaScript that returns the data to my View.
Here is my View:
<label>STATE HERE:</label>
#Html.DropDownListFor(x => x.States, Model.States, new { #class = "chzn-select", id = "stateID" })
<br /><br />
<label>CITY HERE:</label>
#Html.DropDownListFor(x => x.Cities, Enumerable.Empty<SelectListItem>(), new { id = "cityID" })
Here is the JavaScript within my View, and somehow I'm not handling my results correctly once I get them:
$(function () {
$("#stateID").change(function () {
var stateId = $(this).val();
// and send it as AJAX request to the newly created action
$.ajax({
url: '#Url.Action("GetCities")',
type: 'GET',
data: { Id: stateId },
cache: 'false',
success: function (result) {
var citySelect = $('#cityID');
$(citySelect).empty();
// when the AJAX succeeds refresh the ddl container with
$.each(result, function (result) {
$(citySelect)
.append($('<option/>', { value: this.simpleCityID })
.text(this.cityFull));
});
},
error: function (result) {
alert('An Error has occurred');
}
});
});
});
Here is my controller called by the JavaScript:
public JsonResult GetCities(int Id)
{
return Json(GetCitySelectList(Id), JsonRequestBehavior.AllowGet);
}
private SelectList GetCitySelectList(int Id)
{
var cities = simpleDB.simpleCity.Where(x => x.simpleStateId == Id).ToList();
SelectList result = new SelectList(cities, "simpleCityId", "cityFull");
return result;
}
Here are my results from Firbug, which tell me I'm building and getting the data without issue, just not populating my DropDownList correctly:
[{"Selected":false,"Text":"Carmel","Value":"IN001"},{"Selected":false,"Text":"Fishers","Value":"IN002"}]
If anyone has any suggestions as to why the JavaScript fails to populate the dropdrown, please comment, thanks!
I have done this several times with something like this:
Create a partial to popolate dropdown list. Name it DropDownList and put in Shared folder of Views
#model SelectList
#Html.DropDownList("wahtever", Model)
Your create view should be something like this (skipped irrelevant parts)
<script type="text/javascript">
$(function() {
$("#StateId").change(function() {
loadLevelTwo(this);
});
loadLevelTwo($("#StateId"));
});
function loadLevelTwo(selectList) {
var selectedId = $(selectList).val();
$.ajax({
url: "#Url.Action("GetCities")",
type: "GET",
data: {stateId: selectedId},
success: function (data) {
$("#CityId").html($(data).html());
},
error: function (result) {
alert("error occured");
}
});
}
</script>
#Html.DropDownList("StateId")
<select id="CityId" name="CityId"></select>
Carefully note the Empty Select item for CityId and the call of loadLevelTwo at document.ready
And your controller should be like:
public ActionResult Create()
{
ViewBag.StateId = new SelectList(GetAllCities(), "Id", "Name");
return View();
}
public ActionResult GetCities(int stateId) {
SelectList model = new SelectList(GetCitiesOfState(stateId), "Id", "Name");
return PartialView("DropDownList", model);
}
Thank you for your assistance,
It turns out that in my JavaScript below, I was attempting to directly reference the simpleCityID and cityFull fields associated with my data model:
$.each(result, function (result) {
$(citySelect)
.append($('<option/>', { value: this.simpleCityID })
.text(this.cityFull));
Instead, I needed to keep it generic and inline with JavaScript standards of referencing Value and Text:
$.each(modelData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text

Categories