Load data from database on select box onchange event - ember.js

Can anyone guide me how to load data from a database when I change the value in the select box? I tried the following code, but when I try to get the "value" and log it says "undefined."
My Component.js
actions:{
filterStudent(){
let filterInputValue = this.get('value');
console.log(filterInputValue);
let filterAction = this.get('filter');
console.log(filterAction);
}
}
My Controller
actions:
{
filterStudentResults(param)
{
if (param !== '')
{
return this.get('store').query('Students', { studentName: param });
}
else
{
return this.get('store').findAll('Students');
}
}
}
My Component.hbs
<select name="newType" onchange={{action "filterStudent" value="target.value"}} class="form-control">
<option value="" disabled selected>Please Select</option>
{{#each model.Students as |newStudents|}}
<option value="{{newStudents.studentId}}">{{newStudents.studentName}}</option>
{{/each}}
</select>
Am calling the component in the Specific template as
{{bind-dropdown model=model Filter=filterStudentResults}}
Am a newbie to EmberJS and appreciate any help. Thanks in Advance :)

In My-Component.js, does not having value as property, You mean to get it from onchange={{action "filterStudent" value="target.value"}} then your action should receive param,
actions:{
filterStudent(selectedValue){
console.log(selectedValue);
}
}
One more problem, I found upon sending action filterStudentResults to component.
The below one is wrong.
{{bind-dropdown model=model Filter=filterStudentResults}}
As you have defined filterStudentResults in controller, you can create closure action and send it to component, so it should be like,
{{bind-dropdown model=model filter=(action 'filterStudentResults')}}
And it should be invoked with selectedValue from component action,
actions:{
filterStudent(selectedValue){
this.sendAction('filter',selectedValue);//this will call controller method with param
}
}

First you need to check the model is ready and you can do so inside route's afterModel(model) hook.
<select name="newType" onchange={{action "filterStudent" value="target.value"}} class="form-control">
Should be re-write to,
<select name="newType" onchange={{action "filterStudent"}} value={{target.value}} class="form-control">

My controller is not getting invoked from the component the sendAction method is not working.
MyController.js
actions:
{
filterStudentResults(param)
{
if (param !== '')
{
return this.get('store').query('Students', { studentName: param });
}
else
{
return this.get('store').findAll('Students');
}
}
}
am calling the component from the template as follows
{{bind-dropdown model=model filter=(action 'filterStudentResults')}}
My Component js
actions:{
filterStudent(selectedValue){
this.sendAction('filterPartsResults',selectedValue)
}
My Componet file name is bind-dropdown and my contollers name is studentsController. The template name is list-studentDetails.

Related

Using ember computed property(filter) to filter model and using ember-models-table 2 for displaying in table format. It gives no record to show

Trying to display user details using ember-models-table addon. Also wanted to filter the data using a isActive field .Am using ember computed property for that (filter). First time when the page is loading am getting the correct result.But when i try to filter , i could see value for currentfilter is passed correctly but am not getting any results. The table says no records to show.
My .hbs code:
<div class="form-group">
<label for="show">Show:</label>
<select class="form-control" id="show" onchange={{action "filterUpdated" value="target.value"}}>
<option value="null">All</option>
<option value="true">Active</option>
<option value="false">Inactive</option>
</select>
</div>
{{models-table
data=filteredPeople
columns=columns
showColumnsDropdown=false
useNumericPagination=true
filteringIgnoreCase=true
showPageSize=true
}}
My controllers code:
users: alias('model'),
currentFilter: null,
filteredPeople: filter('users', function(user) {
if(this.get('currentFilter') === null) {
return true;
} else {
return user.isActive === this.get('currentFilter');
}
}).property('users', 'currentFilter'),
actions: {
filterUpdated: function (value) {
alert(value);
if (value=== null) {
this.set('currentFilter', null);
}
else {
this.set('currentFilter', value);
}
}
Please help.
After checking , i just noted it was a silly mistake, the filterUpdated method returns string and isActive field needs a boolean value.
I just included the follwing line to change it to boolean.
var isActiveS = (this.get('currentFilter') == 'true');
It worked.

sending actions from within a component in Ember

I'm trying to figure out how to handle in a single place a "login" action, that must be activated from a button click and "enter" keypress;
in my template I've wrapped everything inside a "login-functions" component
//template home.hbs
{{#login-functions}}
<input id="email" type="email" class="validate">
<input id="password" type="password" class="validate">
<div id="login" {{action "login"}}>
{{/login-functions}}
//component components/login-functions.js
export default Ember.Component.extend({
actions: {
login: function() {
var email = $('#email').val();
var password = $('#password').val();
var self = this;
Utils.login(email, password).done(function(res) {
localStorage.setItem('Access-Token', res.data.token);
localStorage.setItem('userId', res.data.user_id);
self.transitionToRoute('feed');
})
.error(function(error) {
//handle error
});
}
},
keyPress: function(event) {
if (event.charCode === 13) {
console.log('login attempt');
this.send('login');
}
}
});
But this doesn't work because the action is not sent from the template button to the component's action and also because from the component I can't perform the transition.
Can someone tell the best way to handle this?
I think it's because your button is part of your home template. Maybe the form should be moved in your login-functions template and be called from your home template by doing {{login-functions}}.
And for the redirection, components can't do them, I'd suggest to call an action using this.sendAction('didLogin') and handle the redirection in your HomeController.
Move the keyPress functions out of the actions.
Updated --- Here is a working demo

Ember: Get the value of textarea from route

I want to get the value of the textarea to use inside my route. I tried using the method below, but the alert shows 'undefined' for that value. How would I go about getting the value of the textarea from the route? I am running the latest version of ember-cli.
Template
{{textarea type="text" value='name'}}
<button {{action 'submit'}} >Send</button>
Route
actions: {
submit: function() { alert(this.get('name'));
} }
You have to pass a variable through action submit, which is bound to textarea value. Usually such a variable is defined in controller (or in wrapper component).
//template
{{textarea type="text" value=name}}
<button {{action 'submit' name}} >Send</button>
//controller
name: 'defaultName'
//route
actions: {
submit: function(val) {
alert(val);
}
}
Working jsbin here

Ember Checkbox getting name of element in callback

If I define a checkbox as follows:
{{input type="checkbox" name="email" checked=controller.isEmailChecked}} Email
In the callback controller.isEmailedChecked, defined as:
isEmailChecked: function(key, value) {
...
}
How do I get the value of name ("email")?
My controller is responsible for displaying multiple checkboxes so I do not want to have to write lines like this:
{{input type="checkbox" name="x" checked=controller.isXChecked}} X
{{input type="checkbox" name="y" checked=controller.isYChecked}} Y
Only to be doing:
ixXChecked: function(key, value) {
// Set or Get
this.set('x', value);
this.get('x');
}
ixYChecked: function(key, value) {
// Set or Get
this.set('y', value);
this.get('y');
}
Can someone point me to the docs please.
Edit: Same applies to actions on Buttons:
<button {{action 'toggleSetting'}}>
</button>
How would I get the name of the element in the toggleSetting callback?
Thanks a lot,
Thanks albertjan but this is more simple:
{{view Ember.Checkbox checkedBinding=someModelProperty}}
It updates the someModelProperty when clicked, and it also sets the correct value initially.
You can pass a parameter to a action like this: {{action "post" "test"}} where the second test can also be a variable. {{action "post" mail}}
As for the checkboxes I'd solve that with an item controller:
{{#each thing in things itemController='thing'}}
{{input type="checkbox" checked=onChecked}}
{{/each}}
and your controller would looks something like:
App.ThingController = Ember.Controller.extend({
needs: ['parent'] //where parent is the name of your other controller.
action: {
isChecked: function() {
this.get('contollers.parent')
.send('checkboxChecked', this.get('model.name'));
}
}
});
Or you can add a component, lets call it named-checkbox. And that would look something like this:
Template (app/templates/components/named-checkbox.hbs):
{{input name=name type="checkbox" checked=onChecked}}
{{yield}}
Component (app/components/named-checkbox.js):
import Ember from 'ember';
import layout from '../templates/components/named-checkbox';
export default Ember.Component.extend({
layout: layout,
name: "",
action: {
onChecked: function() {
this.sendAction(this.get('action'), this.get('name'));
}
}
});
Then you can use it like this:
{{named-component name="email" action=isChecked}}
This will result in the isChecked action being called on the controller with the name as it's attribute:
actions: {
isChecked: function(name) {
this.set('name', !this.get('name'))
}
}

date entries in emberjs templates

When I set {{input value=sDate type='date'}} in a handlebar template in emberjs, I get the html5 datepicker when using Chrome. Unfortunately, html5 datepicker is not supported in Firefox. How do I switch over to the jqueryUI datepicker instead?
The best way would be to create your own component and to call element.datepicker(); in your component's didInsertElement hook.
Here is an [Ember.Component][1] implementation of Bootstrap DatePicker:
Note: You should be able to adapt the setupDatePicker function easily to use jqueryUI datepicker.
date_picker_component.js
Chipmunk.DatePickerComponent = Ember.Component.extend({
setupDatePicker: {
var self = this;
return this.$('.datepicker').datepicker({
separator: "-",
autoclose: true
}).on("changeDate", function(event) {
return self.set("value", self.format(event.date));
});
}.on('didInsertElement'),
formattedValue: {
var value = this.get('value');
if (value) {
return this.format(value);
}
}.property('value'),
format: function(value) {
return moment.utc(value).format("YYYY-MM-DD");
}
});
date-picker.handlebars
<div class="date datepicker" data-date-format="yyyy-mm-dd">
<input class="form-control" size="16" type="text" readonly {{bindAttr value="formattedValue" rel="rel"}}>
<span class="add-on"><i class="icon-th"></i></span>
</div>
Usage:
{{date-picker value=sDate}}