Im trying to display the product data using ng2-smart-table plugin.
I am able to get the products in the browser log, but i need to display the same onChange of a drop down value.
\app\components\layout\blank-page\blank-page.component.html
<form role="form">
<fieldset class="form-group">
<label>Select Category</label><br/><br/>
<select [(ngModel)]="selectedObject" (ngModelChange)="onChange(selectedObject)" name="selectedObject" class="form-control">
<option>--Select Category--</option>
<option *ngFor="let category of categories" [value]="category._id">{{category.category_name}}</option>
</select>
</fieldset>
</form>
//This is where table data is displaying, need to show my data here
<ng2-smart-table [settings]="view_update_items_settings" [source]="view_update_items_smart_data" (userRowSelect)="onUserRowSelect($event)" class="table table-hover table-striped"></ng2-smart-table>
app\components\layout\blank-page\blank-page.component.ts
onChange(categoryid) {
this.productService.getProductsOncategory(categoryid).subscribe(data => {
if (data.success) {
//this.selectedObject = data.mainProducts;
console.log(data)
console.log('Products obtained');
} else {
console.log('Not obtained!');
}
});
}
app\services\product.service.ts
getProductsOncategory(category_id){
console.log(category_id)
let catUrl="http://10.*.*.*:5000/products/getProductsOncategory"
let headers = new Headers();
headers.append('Content-Type','application/json');
let catIdObj = JSON.stringify({category_id:category_id})
console.log(catIdObj)
return this.http.post(catUrl,catIdObj,{headers:headers})
.map((response:Response)=>response.json())
.do(data=>console.log(JSON.stringify(data)))
.catch(this.handleError);
}
On selection of a value from drop down, i get data posted in my browser, i need to display the same in my ng2-smart-table
Bind "view_update_items_smart_data" with the data you obtain from server.
onChange(categoryid) {
this.productService.getProductsOncategory(categoryid).subscribe(data => {
if (data.success) {
//this.selectedObject = data.mainProducts;
console.log(data)
console.log('Products obtained');
this.view_update_items_smart_data.load(data);
} else {
console.log('Not obtained!');
}
});
}
For more information you can refer to
https://akveo.github.io/ng2-smart-table/#/examples/populate-from-server
Related
I'm facing an issue. i have a dropdown contains list of users fetching from database. When i select a user from dropdown it appends on below table and when i select the same user again it again appends on below table as a new row. So i want to stop duplicating same user in table.
Here's my View Code
<div class="form-group col-md-4 " style="display:none" id="user-container">
<label>User</label>
<select id="users" class="form-control" disabled="disabled">
<option value="">Select User</option>
</select>
<p class="validate-error"><span id="users_error"></span></p>
</div>
Here's my JavaScript Code
PostMyData(obj, '/Admin/Meetings/GetUserGroupUsers', (res) => {
if (res.Code === 0 || res.Code === -1) {
alert(res.Message);
}
if (res.Code === 1) {
$('#users').html('');
$('#users').append('<option value="">Select User</option>');
res.Data.map(item => {
$('#users').append(`<option value="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
});
$('#users').prop('disabled', false);
}
I think dynamically giving an id will do this job.Lets say you are giving giving id based of id value, then you can easily find if same id exits or not.
PostMyData(obj, '/Admin/Meetings/GetUserGroupUsers', (res) => {
users = document.getElementById("users");
if (res.Code === 0 || res.Code === -1) {
alert(res.Message);
}
if (res.Code === 1) {
users.html('');
users.append('<option value="">Select User</option>');
res.Data.map(item => {
if(!users.querySelector(item.UserId))
users.append(`<option value="${item.UserId}" id="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
});
users.prop('disabled', false);
}
I don't know what do you mean by duplicating same user in table, If you mean you want prevent duplicating user in the dropDown list you can try on this code, if not, please provide more details about the table you are working on.
...
const usersList= $('#users');
res.Data.forEach(item => {
if(usersList.find(`option[value=${item.UserId}]`).length > 0){
return ; // do nothing
}
usersList.append(`<option value="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
});
...
Select option with ngFor in Angular is showing duplicate values, API returns values with the same department ID for different employees.
This is my HTML snippet, this just gets the data and shows it in the select option dropdown:
<select class="form-control" [(ngModel)]="departmentId" id="department" name="department">
<option value='' disabled selected hidden>Select
Department</option>
<option *ngFor="let data of attendanceLogs" [value]="data.id">
{{data.department_name}}</option>
</select>
getAttendanceLog(){
this.hrService.getAttendanceLogs().subscribe(data => {
if(data.status_code == 200) {
this.attendanceLogs = data.data;
this.rows = this.attendanceLogs;
this.temp = this.attendanceLogs;
} else {
this.snotifyService.error(data.message)
}
},
error => {
this.snotifyService.error("Not able to load the data. Please reload project and try again.");
});
};
I have the following project flow structure:
import_product.html
<div class="row custom_row">
<div class="col-md-2">Additional Duty: </div>
<div class="col-md-2">
<select class="form-control" [(ngModel)]="product.additional_duty_not_no" (change)="changeAddDutyNotSrNo()" required="required">
<option value=" ">-- SELECT --</option>
<option *ngFor="let add_duty_not_no_data of product.addl_duty_not_nos" value="{{ addl_duty_not_no_data.notification_no }}">{{ addl_duty_not_no_data.notification_no }}</option>
</select>
</div>
import_product_component.ts
getAddlNotificationDuty() {
var url = 'api/getBasicNotificationDuty';
var add_duty_not_no_data : any;
var ref = this;
this.jobService.loadRemoteUrl(url)
.subscribe(
data => { add_duty_not_no_data = data},
err => console.error(err),
() => {
if (add_duty_not_no_data.length > 0) {
ref.product.addl_duty_not_nos = add_duty_not_no_data;
}
}
);
}
Now the call is made to the API backend powered by Laravel PHP which successfully returns the desired data in the following array format:
[{"notification_no":"012/39"},{"notification_no":"007/97"},{"notification_no":"999/85"}]
But unfortunately the dropdown in the frontend is not getting populated with the concerned values. There are no errors in the console.
console.log till the .ts component shows objects being returned successfully but it is not getting appended to the dropdown.
Please let me know if you want any more details. Any help will be highly appreciated.
where do you get
basic_duty_not_no_data
from?
also I recommend using slightly different flow with handling ajax call
add_duty_not_no_data: any
getAddlNotificationDuty() {
var url = 'api/getBasicNotificationDuty';
this.jobService.loadRemoteUrl(url)
.subscribe(
data => {
if (data.length > 0) {
this.add_duty_not_no_data = data;
}
},
err => console.error(err)
);
}
I'm trying to generate dynamic form based on the key of document fields and using ng-if attribute in AngularJS.
Ex:
- If field name is "name|string" then populate textfield
- If field name is "name|select" then populate dropdownlist
- If field name is "name|datepicker" then populate datepicker
Following is the code:
<div class="form-group" ng-repeat="(index, formVal) in providerModelData" ng-if="!$first">
<label>{{mySplit(index,0) | uppercase}}</label>
<div ng-if="!mySplit(index,1)">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'datepicker'">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'select'">
<select class="form-control" ng-init="getDropdownData(index,colName)" ng-options="dropdown._id for dropdown in dropdownData[colName]">
<option value="">Select</option>
</select>
</div>
</div>
controller:
$scope.mySplit = function(string, nb) {
var array = string.split('|');
return array[nb];
}
textfields are working fine and populating data but I'm facing issue while populating dropdown fields.
Example: I've two dropdown fields in my mongodb document i.e. city|select and state|select
I'm trying to use ng-options to call function by passing index and colName (document name) to populate dropdownlist but its not working.
Following is the code:
$scope.dropdownData = {};
$scope.getDropdownData = function (query, colName) {
$http.get('/getdropdowndata/', {
params: {
query: query,
colName: colName
}
}).success(function (response) {
$scope.dropdownData[colName] = response;
});
};
Express:
router.route('/').get(function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query.query);
db.collection(query.colName).aggregate([{
"$group":{
"_id":"$"+query.query
}
}],function (err, docs) {
console.log(docs);
res.json(docs);
});
});
Initially I tried calling function in ng-repeat but it was going into infine loop. Then later I tried ng-init options but it only calls or initialize once which is not working in my case. Here I need to call function dynamically and based on that I want to populate dropdown for different fields.
Any help would be appreciated.
Your view is completely messed up as far I see it you are missing
ng-model
for your select input.
Your JSON is improper its missing , before {'id_':'Arizona'}
Try to get response in your controller and push it to array and make use of that array in your View :
$scope.getDropdownData=function(query, colName){
$http.get('/getdropdowndata/', {
params: {
query: query,
colName:colName
}
}).success(function (response) {
var returnArray = [];
alert(JSON.stringify(response));
angular.ForEach(response,function(option){
//parse response and push it to returnArray
returnArray.push(option);
});
return returnArray;
});
}
View :
<div class="form-group">
<select class="form-control" ng-model="selection" ng-options="dropdown._id for dropdown in getDropDownData()">
<option value="">Select</option>
</select>
</div>
Here is the link to Codepen
.
Consider the following solution:
In your controller, set up a variable for the dropdown data:
$scope.dropdownData = {};
Then change your getDropdownData function to:
$scope.getDropdownData=function(query, colName){
$http.get('/getdropdowndata/', {
params: {
query: query,
colName:colName
}
}).success(function (response) {
alert(JSON.stringify(response));
$scope.dropdownData[colName] = response; // This will put data into our html file
});
}
And the HTML for your dropdown case should be:
<div ng-if="mySplit(index,1) == 'select'">
<select class="form-control" ng-init="getDropdownData(index,colName)" ng-options="dropdown._id for dropdown in dropdownData[colName]">
<option value="">Select</option>
</select>
</div>
I used the notorious ngInit to make the call from getting data for the server. Perhaps there's a better way that I didn't consider. But in any case, the idea is to make the call to the server, and save the data in a way that you can fetch it easily from the view.
Edit
I don't know why, but for some reason this solution doesn't work with ng-options. It does, however, work when using it like this:
<select class="form-control" ng-init="getDropdownData(index,colName)">
<option value="">Select</option>
<option ng-repeat="dropdown in dropdownData[colName]" value="dropdown._id">{{dropdown._id}}</option>
</select>
See a simple example here.
Finally I solved it myself. Thanks #Rishab777 and #yarons for guiding me.
Here's the view code:
<div ng-if="mySplit(index, 1) == 'select'">
<select class="form-control">
<option value="">Select</option>
<option ng-model="providerModelData[index]" ng-selected="providerModelData[index]" ng-repeat="dropdown in dropdownData[index]" value="{{dropdown._id}}">{{dropdown._id}}</option>
</select>
</div>
and controller:
$scope.showModal = false;
$scope.toggleModal = function (colId, colName) {
$http.get('/collectiondata/' + colId + '/collectionName/' + colName).success(function (response) {
$scope.colName = colName;
$scope.colId = colId;
for (var key in response) {
if (response.hasOwnProperty(key)) {
if ($scope.mySplit(key, 1) === 'select') {
$scope.getDropdownData(key, colName);
}
}
}
$scope.providerModelData = response;
$scope.showModal = !$scope.showModal;
});
};
$scope.dropdownData = {};
$scope.getDropdownData = function (query, colName) {
$http.get('/getdropdowndata/', {
params: {
query: query,
colName: colName
}
}).success(function (response) {
$scope.dropdownData[query] = response;
});
};
Now the issue is ng-selected="providerModelData[index]" is not working and its showing last item as selected only.
I'm having some issues with setting up the validation for a select. the code reads like
HTML
<form name="customerForm" novalidate="novalidate" data-ng-submit="submit()">
<li class="has-error" data-ng-if="customerForm.country.$error.required">
{{ 'CountryRequired' | translate }}
</li>
<label for="ddlCountries">{{ 'Country' | translate }}</label>
<select id="ddlCountries" name="country" class="form-control"
data-ng-model="selectedCountry"
data-ng-options="option.text for option in countries track by option.id"
data-ng-change="countryChange()" required="required">
<option value="" selected="selected">{{ 'SelectCountry' | translate }}</option>
</select>
</form>
JS Controller
$scope.countries = [];
countryService.getCountries().then(function (results) {
$scope.countries = results.data;
}, function (error) {
console.log(error.data.message);
});
$scope.$watch('customer.country', function (id) {
// Select the value on the dropdown list
$scope.selectedCountry = { id: id };
});
$scope.countryChange = function () {
$scope.customer.country = $scope.selectedCountry.id;
};
$scope.submit = function () {
if ($scope.customerForm.$valid) {
customerService.postCustomerForm($scope.customer).success(
function (data, status, headers, config) {
/*success callback*/
}).error(function (data, status, headers, config) {
alert("Submitting form failed!");
});
} else {
console.log("Invalid fields");
}
};
I've tried different things like setting selected="selected" on the select but didn't work. Also tried required and ng-required without luck.
Am I missing something or doing it wrong?
The problem is that you reset select model so original one you defined is replaced with a new one. Look at this piece of code:
$scope.$watch('customer.country', function(id) {
$scope.selectedCountry = {id: id};
});
In this code you overwrite $scope.selectedCountry with totally new object, so the model which has been used for setting up form validation is destroyed and new validation is never build.
In your case you can update selectedCountry model like this:
$scope.$watch('customer.country', function(id) {
if (id) {
$scope.selectedCountry.id = id;
}
});
But better, remove wather all together, you don't need it since you have ngChange directive, where you can update selectedCountry.id.
Demo: http://plnkr.co/edit/CXDRdRYxZn38FnanOqid?p=preview