Get value from a database and set it as selected value of a dropdownlist using Angularjs - angularjs

I get some values from a database. With one of the values I get, I would like to have that as a selected value in the dropdownlist when another dropdownlist changes. Please see code below:
index
<div class="form-group">
<select ng-model="editProject.ClientId" name="client_id" ng-options="item as item.Company for item in clientList" class="form-control">
</select>
<div>-->{{editProject.ClientId}}</div> <=== This is to see if I am getting the value from js
<span style="color: red;" ng-show="formEditProject.client_id.$touched && formEditProject.client_id.$invalid">Select a client</span>
</div>
js
//=== This is the client list in the dropdown list ===>
$scope.editClient = {
"ClientId": null,
"Company": null,
"ContactPerson": null,
"EmailAddress": null
}
//== Retrieves clients from the database on page load ===>
$scope.getClients = function () {
return $http.get('/Clients/GetClients')
.then(function (response) {
$scope.clientList = response.data;
});
};
//== Event when a different dropdownlist is changed ===>
$scope.onProjectEditChange = function () {
console.log($scope.selectedProjectId.Id);
$http({
url: '/Project/GetProjectByProjectId',
params: {
"id": $scope.selectedProjectId.Id
},
method: 'post'
})
.then(function (response) {
$scope.editProject.Id = response.data.Id;
$scope.editProject.Description = response.data.Description;
$scope.editProject.ClientId = response.data.ClientId;
$scope.editProject.ProjectLead = response.data.ProjectLead;
$scope.editProject.IsApproved = response.data.IsApproved;
});
}
I am able to see the clientId change in the <div>-->{{editProject.ClientId}}</div> but it doesn't change the selected value of the dropdownlist.

Use ng-change option and check it
<div class="form-group">
<select ng-model="editProject.ClientId" name="client_id" ng-options="item as item.Company for item in clientList" class="form-control" ng-change='changeSelectedItem(editProject.ClientId")'>
</select>
<div>-->{{editProject.ClientId}}</div> <=== This is to see if I am getting the value from js
<span style="color: red;" ng-show="formEditProject.client_id.$touched && formEditProject.client_id.$invalid">Select a client</span>
</div>
$scope.changeSelectedItem = function(client){
$scope.editProject.ClientId= client.ClientId;
}

Related

How to I use http.post in angular js to retrieve the rows of my datatable that are checked?

Hi I have a datatable with id, name, etc. and have checkboxes added within the angular js
e.g.
vm.dtColumns = [
DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable()
.renderWith(function(data, type, full, meta) {
vm.selected[full.ID] = false;
return '<input type="checkbox" class="checkedtestids" ng-model="showCase.selected[' + data.ID + ']" ng-click="showCase.toggleOne(showCase.selected)">';
}),
I have checkboxes that can select all rows from the header or individually.
I have also got a var that keeps the id and changes the boolean state from true to false depending on the checkbox being checked or not.
var vm = this;
vm.message = '';
vm.someClickHandler = someClickHandler;
vm.selected = {};
vm.selectAll = false;
vm.toggleAll = toggleAll;
vm.toggleOne = toggleOne;
My html code to display this vm.selected = {}; is as follows:
<div ng-controller="WithAjaxCtrl as showCase">
<blockquote>Please click on a row</blockquote>
<p class="text-danger">
You clicked on: <strong>{{ showCase.message }}</strong>
</p>
<table datatable="" dt-options="showCase.dtOptions"
dt-columns="showCase.dtColumns" class="row-border hover"></table>
<p class="text-danger">You selected the following rows:</p>
<p>**<pre ng-model="showCase.selected">{{ showCase.selected |json }}</pre**>
If I click on these ids :
enter image description here
Then the following is reflected below:
enter image description here
{
"2457937718692": true,
"2457985718634": false,
"2454757950532": true,
How do I send this array vm.selected that indicates checked or not to my java spring controller which will then use them for another purpose?
I have tried to use $http.post() and $http.get() without success.
You don't need to pass the ID in the ng-model to identify the selected checkboxes because the array of object is bound to the view, instead you can pass the boolean variable and use filter directive https://docs.angularjs.org/guide/filter.
Eg.:
JAVASCRIPT
vm.data = ['a','b','c'];
var selected = [];
var vm.filterSelectedData = function(){
selected = $filter('filter')(data, {checked: true});
}
HTML
<div ng-repeat="element in showCase.data">
<input type="checkbox" class="checkedtestids" ng-model="element.selected" ng-change="showCase.filterSelectedData()" />
</div>
to send the selected items to the server you just need to create a json object with the array of those selected items.
http.post('url', {selectedItems:selected})
.success(function(){ // calback function })
.error(function(){ // error function })
see plunker
https://plnkr.co/edit/iJf7onwLUKckQDzBP2pT

Retrieve Selected Option Value From HTML DropDownList

I've a DropDownList where user has to select options and save it to database. I am using the following with AngularJs:
<select>
<option>----Please Select Sub-Category----</option>
<option ng-repeat="m in Categories" value="{{ m.CategoryId }}" ng-model="saveProducts.CategoryId">{{ m.Category }}</option>
</select>
I can show the values in the above DropDownList but stuck to retrieve the value from the selected and pass it to the scope. I've tried even this, a silly one:
<select>
<option>----Please Select Sub-Category----</option>
<option ng-repeat="m in Categories" value="{{ m.CategoryId }}" ng-model="m.CategoryId">{{ m.Category }}</option>
</select>
But that will not work. saveProducts is the object (scope) where I am passing values but is there any easy way where I can pass option value with the above procedure?
Here what I am doing to save data in database and it works fine except the option value, it's unable to retrieve values with the above:
productApp.controller('addProductController', function ($scope, $http) {
$scope.addData = function () {
$http({
method: 'POST',
url: '/Product/AddProductsToDb',
data: $scope.saveProducts
}).success(function () {
$scope.saveProducts = null;
}).error(function () {
alert('Failed');
});
}
});
This is the output I have and just want to pass the option value from it:
Update 1 - This is what I've tried but I can show the value in the alert method using as follows:
<select ng-model="saveProducts.ParentId"
ng-options="m.Category for m in Categories track by m.CategoryId">
<option value="">----Please Select Sub-Category----</option>
</select>
AngularJs Controller:
productApp.controller('addProductController', function ($scope, $http) {
$scope.addData = function () {
angular.forEach($scope.saveProducts, function (model, index) {
$scope.saveProducts.ParentId = (model.CategoryId);
});
alert($scope.saveProducts.ParentId);
$http({
method: 'POST',
url: '/Product/AddProductsToDb',
data: $scope.saveProducts
}).success(function () {
$scope.saveProducts = null;
}).error(function () {
alert('Failed');
});
}
});
Note: It saves TextBox input value but stuck with DropDownList. Unable to retrieve select option value and save it to database.
You should have a property to store the selected option. You can use ng-options to render the dropdown.
<select ng-model="selectedCategory"
ng-options="option.Category for option in Categories track by option.CategoryId ">
<option value="">Select Option</option>
</select>
Now your select element's ng-model is set to selectedCategory. So in your add method you can access that and use that for saving.
$scope.addData = function () {
console.log($scope.selectedCategory);
//to do : use selectedCategory
}
Use ngOptions. Depending on the structure of your Categories data, you could do something like:
<select ng-options="m as m.yourProperty for m in Categories" ng-model="selected"></select>
Then, in Angular...
$scope.selected = $scope.Categories[0];
Read the ngOptions documentation to tweak according to your needs.

Angular populate from JSON through httpd and then choose selected

I'm fairly new to Angular and i'm trying to do something quite simple. I want to populate a dropdown box and have the selected value from database as selected option. Here is my dropdown code.
<select ng-options="option.fname+' '+option.lname for option in students track by option.id"
class="form-control"
name="studentId"
ng-model="selectedStudent"
id="studentId"
ng-change="loadStudent()"
>
<option value="">Please choose a student</option>
</select>
Now, in my module and the controller, i have this code which populates the dropdown and i can see the options (student.id, student.fname , student.lname):
$scope.students = {};
$scope.selectedStudent = null;
$scope.populateStudents = function() {
$http({
method: 'POST',
url: 'ajax/getStudents',
data: { teacherId: 0 }
}).success(function (result) {
$scope.students = result;
$scope.selectedStudent = 4;
});
}
This runs i guess on page load as i have this :
Then on the above script and after the $scope.students is loaded, i write
$scope.selectedStudent = 4; which I want to preselect the student with student.id = 4.
What happens though is that the default
<option value="">Please choose a student</option> is becoming <option value="" select="selected">Please choose a student</option> instead of the student with id 4.
What am I doing wrong ?
Thank you.
When you use ngOptions with an array of complex objects, you must use an identical complex object to "select" one of the options, not just a number. So, once your $http call has returned, find the item in the list with the id you want and assign your scope variable to be the entire student object:
$http({
method: 'POST',
url: 'ajax/getStudents',
data: { teacherId: 0 }
}).success(function (result) {
$scope.students = result;
angular.forEach($scope.students, function(student) {
if (student.id == 4) {
$scope.selectedStudent = student;
}
});
});
If you add the as statement to your ng-repeat you can select the student by id like so:
<select ng-options="option.id as option.fname+' '+option.lname for option in students track by option.id"
class="form-control"
name="studentId"
ng-model="selectedStudent"
id="studentId"
ng-change="loadStudent()"
>
<option value="">Please choose a student</option>
</select>
$scope.selectedStudent = { id: 4 };
I prefer to use lodash or underscore to find an item in a list rather than using forEach:
$scope.selectedStudent = lodash.find($scope.students, { 'id': 4 });

angularjs and grails 2.5.0 save success, no errors but not saving to database

I've been looking for similar situations like mine has and I've seen that it is common to have this error but I can not find the right solution with my problem. I would really appreciate any help.
My problem right now is that when I execute this it return and HTTP 200 and also prints a line on my terminal which confirms me that it creates the JSON file. There are no errors but when I checked on my database, there's nothing in it.
What I've tried so far:
newBook.save(flush: true)
edit my datasource from create-drop to update (but my whole database disappears so I returned the data. I only need to save it during a demo so I understand that the data will be lost every time the application restarts)
Postman GET and POST
GET: 200 OK
POST: 200 OK
but when I GET again, nothing is showing
debugging using console and println (but there might be something that I missed since I'm just starting to learn both AngularJS and Grails)
I am hoping that these data can give a detailed information about my problem, I am open for any questions.
Here are my sample codes:
back-end codes: Grails 2.5.0
Domain class
class Book {
String name
int page
boolean new
static belongsTo = [student: student]
static constraints = {
}
}
Controller
import grails.converters.JSON
import org.springframework.security.access.annotation.Secured
#Secured('permitAll')
class BookController {
def index() {
render Book.list() as JSON
}
def save() {
def newBook = new Book(request.JSON)
newBook.save(flush: true)
println request.JSON
render(['success': true] as JSON)
}
def show() {
def Book = Book.get(params.id)
render Book as JSON
}
}
front-end codes: AngularJS
Controller
app.controller('Book', function($scope, store, $state, bookFactory){
$scope.book = {}
$scope.saveBook = function() {
$scope.book.assessment = $scope.getBook();
console.log($scope.book);
bookFactory.save($scope.book,function (result){
console.log(result)
}, function (error) {
console.log(error)
})
}
$scope.getBook = function() {
var result = "";
if ($scope.book.page > 10){
result = "many pages";
}else if ($scope.book.new && $scope.book.page > 20){
result = "new and many pages";
}else {
result = "old book";
}
return result;
};
})
Service
app.factory('bookFactory', ['$resource', function ($resource) {
return $resource('api/book',
{
'update': {method: 'PUT'}
})
}])
app.js
.state("book", {
url: "/book",
templateUrl: "assets/app/partials/book.html",
controller: 'Book',
data: {
requiresLogin: true
}
})
HTML
Book Name:
<input type="text" ng-model="book.name" name="bookName" required="" class="form-control" />
Number of Pages:
<input type="number" ng-model="book.page" name="numberPage" required="" class="form-control" placeholder="Number of Pages"/>
Bought within the last 30 days?
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="new" value=true ng-model="book.new" >
<font color=green>YES</font>
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="new" value=false ng-model="book.new">
<font color=red>NO</font>
</label>
</div>
</div>
<a ui-sref="book" class="btn btn-primary" name="bookBtn" ng-click="saveBook()"> Next </a>

ngResource GET with filter values

I'm writing a small test application where I can retrieve my customers from a parse.com database.
I have the following form in html
...
<body ng-app="myApp">
<div ng-controller="CustomerController">
<button ng-click="getCustomers()">Get customers</button>
<ul>
<li ng-repeat="customer in customers">{{ customer.name }}</li>
</ul>
</div>
</body>
...
My angular app is the following:
Module
var app = angular
.module('myApp', ['ngResource'])
.constant('myConfig', {
'api_url': 'https://api.parse.com/1/classes/',
'parse_application_id': 'xxxxxxxxxxxxx',
'parse_rest_api_key': 'xxxxxxxxxxxxx'
});
Factory
app.factory('CustomersService', function($resource, myConfig) {
return $resource(myConfig.api_url + 'Customer', {}, {
query: {
method: 'GET',
isArray: false,
headers: {
'X-Parse-Application-Id': myConfig.parse_application_id,
'X-Parse-REST-API-Key': myConfig.parse_rest_api_key
}
},
create: {
method: 'POST',
headers: {
'X-Parse-Application-Id': myConfig.parse_application_id,
'X-Parse-REST-API-Key': myConfig.parse_rest_api_key
}
}
})
});
Controller:
app.controller('CustomerController', function($scope, CustomersService, CustomerService) {
$scope.getCustomers = function() {
CustomersService.query().$promise.then(function(result) {
$scope.customers = result.results;
});
};
});
So when I click my button, everything works like it should.
But I also want to add a filter by name when I want to retrieve customers from the database.
When I execute the following in Postman
https://api.parse.com/1/classes/Customer?where={"name":"aaaaa"}
this works and only gets the customer with the name "aaaaa". So I know that the syntax is OK.
So I will add a textbox where the user can enter a customername and after that I want to click on the search button.
But how can I manage the ?where={"name":"aaaaa"} into the angular stuff when I click the button? I also want to expand the filter with other columns from that customer.
Something like this should work (assuming everything goes in the where object)
Add some search fields that bind to a scoped object's properties. We'll call it search
<label for="search_name">Name</label>
<input type="text" ng-model="search.name" name="name" id="search_name">
<label for="search_city">City</label>
<input type="text" ng-model="search.city" name="city" id="search_city">
Then you can execute the query action with
CustomersService.query({where: $scope.search}).$promise...
That should create a query param like
?where=%7B%22name%22%3A%22aaaaa%22%2C%22city%22%3A%22London%22%7D
which is the URI encoded value
?where={"name":"aaaaa","city":"London"}

Resources