Populating a dropdownlist with AngularJS - angularjs

I want to populate a dropdownlist with values from a table I created called Venues. This table has only two things in it, the Venue Id and Name.
I created a Code First Entity Data Model from the database that holds the table Venues and I created this method in my controller:
public JsonResult GetVenues()
{
using (ReservationsModel dc = new ReservationsModel())
{
var v = dc.Venues.OrderBy(a => a.Name).ToList();
return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
then in my script i added:
$scope.selectedVenue = null;
$scope.venues = [];
$http.get("/home/getvenues").success(function (data) {
angular.forEach(data, function (item) {
venues.push(item.Name);
});
$scope.list = venues;
}).error(function (status) {
alert(status);
});
$scope.selectedVenue = $scope.venues[i].Name;
and in my view I have:
<select ng-model="selectedVenue" ng-options="item in venues">
<option value="">-- Select Venue --</option>
</select>
I came from these guides:
http://www.dotnetawesome.com/2016/04/implement-event-scheduler-calendar-angularjs.html
How can I populate a select dropdown list from a JSON feed with AngularJS?
https://jsfiddle.net/pravinmagar/Ljgk8oy0/

Let's see your code.(check the comments)
$scope.selectedVenue = null;
$scope.venues = [];
$http.get("/home/getvenues").success(function (data) {
angular.forEach(data, function (item) {
// this should be $scope.venues, not just venues
venues.push(item.Name);
});
// you don't need another scope variable
$scope.list = venues;
}).error(function (status) {
alert(status);
});
// as $scope.venues is an array of Names, $scope.selectedVenue = $scope.venues[i] is enough
$scope.selectedVenue = $scope.venues[i].Name;
So,
$scope.venues = [];
$http.get("/home/getvenues").success(function (data) {
angular.forEach(data, function (item) {
$scope.venues.push(item.Name);
});
}).error(function (status) {
alert(status);
});
// if i has declared a value somewhere in your code, then
$scope.selectedVenue = $scope.venues[i];
and in template,
<select ng-model="selectedVenue">
<option value="">Select Venue</option>
<option ng-repeat="venue in venues" ng-value="venue">{{venue}}</option>
</select>

Your html part is ok, just need following modification in controller JS:
access venues like $scope.venues while pushing
assign default selected inside .success because http.get() is async.
Code:
$scope.selectedVenue = null;
$scope.venues = [];
$http.get("/home/getvenues").success(function (data) {
angular.forEach(data, function (item) {
$scope.venues.push(item.Name);
});
$scope.selectedVenue = $scope.venues[i].Name; // i must be declared in your js
}).error(function (status) {
alert(status);
});

Related

ng-options in angularjs does not get rebind after change in collection

I am using dataFactory for getting collection by making api call.
productApp.factory("productDataFactory", function($http){
return {
getUnits: function() {
return $http.get('/unit').then(function(resp) {
return resp.data; // success callback returns this
});
},
getCommodities: function() {
return $http.get('/commodity').then((resp) => {
return resp.data;
})
}
};
});
I use commodities collection in ng-options to populate options of select element.
<select ng-model='selected_Commodity' ng-change="updateGST()" name="commodity" id="commodity" ng-options = " c as c.commodity_name for c in <%= JSON.stringify(commodities) %> track by c "class="form-control selectpicker" data-size="4" data-live-search="true" data-index="5" >
<option value="" ng-hide='selected_Commodity'>Select Commodity</option>
</select>
I am updating collection on a event. I am getting updated values in log. But It does not get reflected in my view.
var getCommodities = function() {
var deferred = $q.defer();
productDataFactory.getCommodities().then((data) => {
if (data.type === 'success') {
debugger;
console.log("Inside factory ");
console.log(JSON.stringify( data.commodities ));
deferred.resolve(data.commodities);
} else {
// $scope.commodities = [{name : data.type + data.msg}]
deferred.reject([{name : data.type + data.msg}]);
}
})
return deferred.promise;
}
$('#commodityModal').on('hide.bs.modal', function () {
$scope.commodities = []
getCommodities().then((data) => {
$scope.commodities = data
console.log("Inside Hide ");
console.log(JSON.stringify( $scope.commodities ));
$("#commodity").selectpicker('refresh')
console.log("Refreshed");
})
})
Please help me how can I rebind my select elements with updated values.
Put this line inside a timeout like this and add timeout as a dependency
$timeout(function(){
$("#commodity").selectpicker('refresh');
});
Change the ng-options
FROM
ng-options = " c as c.commodity_name for c in <%= JSON.stringify(commodities) %> track by c "
TO
ng-options = " c as c.commodity_name for c in commodities track by c "

Angular 1:Build dropdown box dynamically

I am new to Angular 1,so I am stuck with building a dropdown box dynamically using angular.
Below is my code
var app = angular.module('myApp', []);
app.controller('TestCtrl', function($scope, $http) {
I have created an onchange function getTypeName() and have passed the parameters using get method and retrieved the result as json .
$scope.getTypeName = function (type) {
$http.get('get-type-name',
{ params:
{
type: type
}
}).then(
function(response){
var data = response.data;
for(i = 0; i < data.length; i++) {
//code to build dropdown
}
},
);
}
});
Below is my response,
[
{"id":"001","name":"ABC"},
{"id":"002","name":"DEF"},
{"id":"003","name":"GHI"}
]
I want to build a dropdown box using this response within the get method function success using for loop.Please provide a solution to solve this out.
you do like this
in app.js
$scope.getTypeName = function (type) {
$http.get('get-type-name',
{ params:
{
type: type
}
}).then(
function(response){
$scope.data = response.data;
},
);
}
});
in your html
<select id="ddl" model="ddldata" typeof="text"required>
<option data-ng-repeat="ProjectName in data" value="{{ProjectName.id}}" ng-bind={{ProjectName.name}}">
</select>
You can try this,
$scope.yourOptions = [];
$scope.getTypeName = function (type) {$http.get('get-type-name',
{ params:
{
type: type
}
}).then(
function(response){
var data = response.data;
$scope.yourOptions = data;
},
);
}
});
in html,
<select class="form-control" ng-model="whatever" >
<option ng-repeat="x in yourOptions " value="{{x.id}}">{{x.name}}</option>
</select>
Here is an example of dynamically populating select options from an http get https://plnkr.co/edit/7PS7LBBNZA2cNzMorrB9?p=preview
<select ng-model="selectedItem">
<option ng-repeat="o in options">{{o.name}}</option>
</select>
$scope.getTypeName = function() {
$http.get('https://jsonplaceholder.typicode.com/users').then(
function(result) {
$scope.options = result.data;
},
function(error) {
console.log(error);
}
);
};

No popup window with AngularJS and typeahead

I have a problem with the typeahead directive. I try to get datas from my datas from my service via $http.get.
In the console output I can see that my datas are coming from the service but I don't get the popup window of the results.
Here is my code:
Html Template:
<input type="text" class="form-control" placeholder="Kundensuche" ng-model="selectedCompany" typeahead="c for c in companies($viewValue)" typeahead-no-results="noResults" typeahead-min-length="3">
Service:
var _search = function (route, id) {
return $http.get(serviceBase + 'api/' + route + '/search/' + id);
};
serviceHelperFactory.search = _search;
Controller:
$scope.companies = function (val) {
var output = [];
var promise = serviceHelper.search('companies', val);
promise.then(function (result) {
result.data.forEach(function (company) {
output.push(company.companyName);
//output.push(company);
});
console.log(output);
}, function (error) {
adminInvoiceService.serviceErrorMessage(error);
});
return output;
}
Thanks!
Ok, I fixed it!
For all with the same problem here is my solution!
$scope.companies = function (val) {
return $http.get('http://localhost:5569/api/companies/search/'+val).then(function (res) {
var companies = [];
console.log(companies);
res.data.forEach(function (item) {
companies.push(item);
});
console.log(companies);
return companies;
});
};

Unexpected binding behaviour

I have select list i set default option to be chosen. what happen is for few second it works then it disappear and the blank option in the list is chosen as default.
<div class="form-group">
<select class="form-control" ng-model="item.action" ng-options="option.value as option.title for option in options">
</select>
</div>
i want to set defualt option to be chosen :
so my controller look like this:
$scope.item = {};
$scope.options = [{
title: 'On entering',
value: 'enter'
}, {
title: 'On exiting',
value: 'exit'
}];
$scope.item.action= $scope.options[0].value;
$scope.profile = me.getUser();
$scope.profile.then(
function(user) {
$scope.owner = user;
$scope.item = {};
$scope.item.data = '';
$scope.item.published = true;
$scope.item.action= $scope.action;
$scope.item.owner = $scope.owner.displayName;
},
function(response) {
console.log(response);
}
);
me is a service that fecth the user data.
the reason why am defining $scope.item = {}; again is because i can't apend the displayName to the $scope.item out of the scope.
I commented this part of the code and it works well:
$scope.profile = me.getUser();
$scope.profile.then(
function(user) {
$scope.owner = user;
$scope.item = {};
$scope.item.data = '';
$scope.item.published = true;
$scope.item.action= $scope.action;
$scope.item.owner = $scope.owner.displayName;
},
function(response) {
console.log(response);
}
);
But now i can't figure out how to build my item object to send it in HTTP request

Angularjs not two way binding for select with multiple

I have a select like:
<select multiple ng-multiple="true" ng-model="selectMulti" ng-options="br.Name for br in branches"></select>
Scope objects in controller are as below:
vehicleFactory.getBranches().success(function (data) {
$scope.branches = data;
}).error(function (data) {
$scope.loading = false;
});
vehicleFactory.getVehicle().success(function (data) {
$scope.vehicle = data;
$scope.selectMulti = $scope.vehicle.AssociatedBranches;
}).error(function (data) {
$scope.loading = false;
});
It is not selecting multiple items in select as it was not binding.
What is wrong in it.
When you use <select multiple..> the ViewModel of it is an array (unlike <select> without multiple).
So, say you have:
$scope.branches = [{...}, {...}, ...];
and the View:
<select multiple ng-model="selectMulti" ng-options="br.Name for br in branches">
</select>
Then, if you would like to select default values, your $scope.selectMulti should be an array of these values:
$scope.selectMulti = [$scope.branches[0], $scope.branches[1]];

Resources