angular js select box item missing after refresh - javascript

I trying to set drop-down box display the default item. First, item in drop-down box able to display correctly and I can select the item in order to save into database. Everything working fine, the problem is after I refresh the page, the default item always is empty, it should display the item that I save.
HTML
<select class="form-control" ng-model="sst_type" ng-options="type for type in
sst_types" ng-change="changeSstType(sst_type)"></select>
JS
.controller('sstCtrl', function ($scope, $rootScope, Module, settings,
toastr, actionBar, $uibModal) {
// scope properties
$scope.loading = true;
$scope.sst_types = ['Sotong', 'Bento'];
$scope.sst_all = [];
// scope functions
$scope.getSst = function () {
Module.getSst().then(function (res) {
$scope.loading = false;
if (res.sst_all) {
angular.forEach(res.sst_all, function (v) {
$scope.sst_all.push({
id: v.id,
name: v.name,
value: v.value,
percentage: (v.value * 100).toString(),
type: v.value == 0 ? 'Sotong' : 'Bento'
});
});
}
});
};

You need to return the id of the saved item from server. You can do that in the Module.getSst() call.
In foreach set $scope.sst_type to the matching one.
Good luck

Related

set default value in dynamic dropdown angularjs

please help me with my problem I'm a little new to angularjs, my problem is that I need to be able to set the default value in the select option when there is only one item because it's a dynamic select option, it has another dropdown with many items but it's okay , what is needed when only one item must be selected in the select option using ng-options
<select class="form-control form" ng-model="relatedTo" style="height: 40px;" ng-options="c.CUSTCODE as c.CUSTNAME + ' - ' + c.CUSTCODE for c in customers | filter:code" > </select><span style="color:red" ng-show="type === 9 || type !== 9"></span>
ANGULARJS
$http.post('commandCenter.aspx/allCustomer', {}).then(
function onSuccess(response) {
$scope.customers = JSON.parse(response.data.d);
console.log($scope.customers); },
function onError(response) {
console.log('error !!! ');
});
Picture no.1 It's okay in this picture because he has a lot of list of items.
Picture no.2 When there is only one item, it must be default or selected.
What #MrJami said. In code something like
$http.post('commandCenter.aspx/allCustomer', {}).then(
function onSuccess(response) {
$scope.customers = JSON.parse(response.data.d);
if ($scope.customers.length === 1) {
$scope.relatedTo = $scope.customers[0].CUSTCODE;
}
console.log($scope.customers); },
function onError(response) {
console.log('error !!! ');
});

Semantic UI dropdown with angular not clear selected value

I've created a small sample of what is happening.
http://plnkr.co/edit/py9T0g2aGhTXFnjvlCLF
Basically, the HTML is:
<div data-ng-app="app" data-ng-controller="main">
<select class="ui dropdown" id="ddlState" data-ng-options="s.name for s in states track by s.id" data-ng-model="selectedState"></select>
<select class="ui dropdown" id="ddlCity" data-ng-options="c.name for c in cities track by c.id" data-ng-model="selectedCity"></select>
</div>
And the javascript is:
angular.module("app", [])
.controller("main", function($scope, $timeout) {
$scope.selectedState = {id:1,name:"A"};
$scope.selectedCity = {id:1,name:"A.1",stateId:1};
$scope.states = [{id:1,name:"A"},{id:2,name:"B"},{id:3,name:"C"}];
var fakeDataSource = [
{id:1,name:"A.1",stateId:1},
{id:2,name:"A.2",stateId:1},
{id:3,name:"A.3",stateId:1},
{id:4,name:"B.1",stateId:2},
{id:5,name:"B.2",stateId:2},
{id:6,name:"B.3",stateId:2},
{id:7,name:"C.1",stateId:3},
{id:8,name:"C.2",stateId:3},
{id:9,name:"C.3",stateId:3}
];
$scope.$watch("selectedState", function(n,o){
if (n !== o)
$scope.selectedCity = null;
$scope.cities = fakeDataSource.filter(function(x){
return n.id === x.stateId;
});
$timeout(function(){
$(".ui.dropdown").dropdown().dropdown("refresh");
});
})
$timeout(function(){
$(".ui.dropdown").dropdown();
})
})
The problem is when I change the first dropdown to value 'B' or 'C', the value of second dropdown does not change, even it is changed in angular model.
You guys can notice that I've the line $(".ui.dropdown").dropdown().dropdown("refresh") to refresh the values but does not work.
I tried destroy and recreate using $(".ui.dropdown").dropdown("destroy").dropdown() but still does not work.
Any help?
Simply using ngModel won't make the values change dynamically. Take a look at the documentation here: https://docs.angularjs.org/api/ng/directive/ngModel
You can bind the values using ngBind or what I have done is do an onChange to then check the value and change your second drop down accordingly. Something like:
$("#ddlState").on("change", function(e) {
//check $scope.selectedState for it's value, and change #ddlCity/$scope.selectedCity accordingly
});

AngularJS object as selected input for typeahead

I have input field which I am using for autocomplete and populate on the fly by executing http requests. I am getting such object as example:
{
id:1,
name:'ABC'
}
I want to display name for a end user but later on when input has been selected I want to use it as id in my further processing. But ng-model converts my object into the string and I loose my id.
In general all works fine but my issue is that when user select something, lets say string "ABC" it means nothing for me unless I can tied it to "ID" which has been returned by my API. Only if I know ID I can continue future processing.
Could you please help me to figure out, what should I do in order to capture fromSelected as object but still show friendly text to user?
Thanks for any help!
Code:
HTML:
<input type="text" ng-model="fromSelected" placeholder="Country, city or airport" typeahead="place.readableName for place in getPlace($viewValue, 'en')" typeahead-loading="loadingLocations" typeahead-no-results="noResults" class="form-control">
JS:
app.controller('PlaceController', function($scope, $http, searchData) {
$scope.fromSelected = '';
$scope.toSelected = '';
$scope.$watch('fromSelected', function(newValue, oldValue){
if (newValue !== oldValue) searchData.setTravelFrom(newValue);
});
$scope.$watch('toSelected', function(newValue, oldValue){
if (newValue !== oldValue) searchData.setTravelTo(newValue);
});
// Any function returning a promise object can be used to load values asynchronously
$scope.getPlace = function(term, locale) {
return $http.get('http://localhost:8080/api/places/search', {
params: {
term: term,
locale: locale
}
}).then(function(response){
return response.data.map(function(item){
return {
'id': item.id,
'name': item.name,
'readableName': item.name + ' (' + item.id + ')'
};
});
});
};
});

Why is this select2 control not populating with dynamic data through an AngularJS controller?

In a template, I have:
<div ng-controller="projectListController as projects" class="pull-right" id="projectListDropDown">
<select ui-select2 id="projectListDD" placeholder="All" class="width240" ng-model="projects.projectSelection">
<option value=""></option>
<option ng-repeat="item in projects.projectList" value="{{item.WebsiteName}}">{{item.WebsiteName}}</option>
</select>
</div>
I want to populate the dropdown list from projectList below:
app.controller('projectListController', ['$rootScope', '$scope', '$log', 'abstractDataFactory', 'customUIFunctions', 'globalContainer',
function ($rootScope, $scope, $log, abstractDataFactory, customUIFunctions, globalContainer) {
dashboardGlobals = this.dashboardGlobals = globalContainer.dashboardGlobals;
var dataFactory = new abstractDataFactory("/odata/ProjectList");
var projectController = new abstractDataFactory("/Projects/ChangeCurrentProject") // load up projectDashboardDTO
this.selectProjectPlaceholder = "Loading Projects . . .";
this.filterItems = [
{ id: 1, text: 'Item1' },
{ id: 2, text: 'Item2' },
{ id: 3, text: 'Item3' },
{ id: 4, text: 'Item4' }
];
this.projectList = [];
// TODO; keep a global list of projects
// Get a list of current projects
dataFactory.getList("") // no parameters
.success(function (result) {
this.projectList = result.value; //<- array of objects is returned
dashboardGlobals.projectList = result.value;
this.selectProjectPlaceholder = "Select a project . . . "
$("#projectListSelection").select2({ width: '240' });
})
.error(function (error) {
customUIFunctions.showError("Data Error - Unable to Load Project List"); // use default error message
console.log("data error");
});
I have confirmed that there is data in result.value but the list remains blank.
However, when I use projects.filterItems in the ng-repeat, (along with id and text field names) the list is populated.
I also want the changed value to be globally accessible in Angular, so I injected my own globalContainer service into this controller, and whenever the page is refreshed, I want to ensure the selected value remains consistent, rather than resetting.
-- UPDATE --
The problem seems to be in the .success area, this.projectList is undefined. If I do var projectList = this.projectList = [] no error, but this doesn't seem right.
So the issue is with trying to define the variables after the fact, and using Controller as....
How can I get this working?
After reading something about half way down the page, here, and a bit more further understanding about the difference between $scope and this, in how they work in .success, I declared vm as a top-level this:
var vm = this;
vm.dashboardGlobals = globalContainer.dashboardGlobals;
var dataFactory = new abstractDataFactory("/odata/ProjectList");
var projectController = new abstractDataFactory("/Projects/ChangeCurrentProject") // load up projectDashboardDTO
vm.projectList = [];
.
.
.
dataFactory.getList("") // no parameters
.success(function (result) {
vm.projectList = result.value;
vm.dashboardGlobals.projectList = result.value;
vm.selectProjectPlaceholder = "Select a project . . . "

twitter bootstrap typeahead not working

I am working on twitter bootstrap typeahead and i am stuck as i am not getting any error and yet the auto complete is not working.
this is my input field
<input type="text" id="autocomplete" />
and this is my script
<script>
$('#autocomplete').typeahead({
source: function(process) {
var data = <?php Widgets::allProducts() ?>;
process(data);
},
matcher: function(item) {
return
item.name.toLocaleLowerCase()
.indexOf(this.query.toLocaleLowerCase()) != -1;
},
highlighter: function(item) {
return item.name;
},
updater: function (item) {
alert(JSON.parse(item).value);
return JSON.parse(item).name;
}
});
</script>
this is how my var data looks like
var data = [{"name":"Acne.org","id":"5"},{"name":"AcneFree","id":"6"},{"name":"Alpha Hydrox","id":"16"},{"name":"AmLactin","id":"17"},{"name":"Astara","id":"21"}];
What i want to do is get the product name listed (which is name in var data ) and upon selecting the product redirect the user to product page (with the help of product id which i am getting in var data as id).
I am just lost at this stage as i am not getting any error. I will appreciate any push to right direction.

Categories

Resources