Populate checkbox values with model data in Ember.js - javascript

I have an ember application which has a number of users. Each of these users can be associated with a number of subjects. So I have a subjects model:
App.Subjects = DS.Model.extend({
subject : DS.attr('string'),
});
App.Subject.FIXTURES = [{
id: 1,
name: 'Sales',
}, {
id: 2,
name: 'Marketing',
}
];
and a users model:
App.User = DS.Model.extend({
name : DS.attr(),
email : DS.attr(),
subjects : DS.hasMany('subject'),
});
App.User.FIXTURES = [{
id: 1,
name: 'Jane Smith',
email: 'janesmith#thesmiths.com',
subjects: ["1", "2"]
}, {
id: 2,
name: 'John Dorian',
email: 'jd#sacredheart.com',
subjects: ["1", "2"]
}
];
I am having trouble representing this 1:M relationship in my templates. I have an edit user template (which Im also using to create a user) in which you can select the user's subjects via checkboxes. However, I want these checkboxes to be driven by the data in my subjects model. Is this possible? I have found very little documentation online and am very new to ember development. Here is my template:
<script type = "text/x-handlebars" id = "user/edit">
<div class="input-group">
<div class="user-edit">
<h5>User name</h5>
{{input value=name}}
<h5>User email</h5>
{{input value=email}}
<h5>Subjects</h5>
{{input type="checkbox" value = "sales" name="sales" checked=sales}}
{{input type="checkbox" value = "support" name="support" checked=support}}
</div>
<button {{action "save"}}> Save </button>
</div>
</script>
EDIT: Here is my current userController.js
App.UserController = Ember.ObjectController.extend({
deleteMode: false,
actions: {
delete: function(){
this.toggleProperty('deleteMode');
},
cancelDelete: function(){
this.set('deleteMode', false);
},
confirmDelete: function(){
// this tells Ember-Data to delete the current user
this.get('model').deleteRecord();
this.get('model').save();
// and then go to the users route
this.transitionToRoute('users');
// set deleteMode back to false
this.set('deleteMode', false);
},
// the edit method remains the same
edit: function(){
this.transitionToRoute('user.edit');
}
}
});

what you need to do is change this line in your template:
{{#each subject in user.subject}}
{{subject.name}},
{{/each}}
for this:
{{#each subject in user.subjects}}
{{subject.name}},
{{/each}}
did you notice I changed subject for subjects ?
and, I would also recommend you to change this code in App.SubjectController:
selected: function() {
var user = this.get('content');
var subject = this.get('parentController.subjects');
return subject.contains(user);
}.property()
to this:
selected: function() {
var subject = this.get('content');
var userSubjects = this.get('parentController.subjects');
return userSubjects.contains(subject);
}.property()
that's a better representation of the data.

Related

Filtering an ng-repeat based on multiple values in angular

This is difficult to phrase but:
I have 1 collection called users.
Every user has 3 properies: id, name, skill.
{
_id: 1,
name: 'frank young',
skill: 'java'
},
I have 1 form collects search results upon pressing enter.
<form ng-submit="pushToNewArry(searchTerm)">
<input type="text" ng-model="searchTerm" />
<input type="submit">
</form>
this is not the best way to do this
$scope.newUsers = [];
$scope.pushToNewArry = function(msg) {
$scope.trackedUsers.push(msg);
$scope.searchTerm = '';
};
Question:
How do I create a filter that will run over multiple search terms and create a list proper matches based on the users collections vs inputed values.
<ol ng-repeat = "user in users | filter: trackedUsers">
<li class="names"><span>{{$index}}. </span>{{user.name}}</li>
<li class="skills">{{user.skill}}</li>
</ol>
Upon submission, the user input will be saved and create a new array of users based on inputed values of search. therefore, multiple matching values.
Updated:
JSFiddle
not excatly the same as example above because I keep playing with it.
You mean like this jsfriddle
updated fiddle
updated fiddle2
<div>{{listSearchTerms | json}}</div>
<form ng-submit="saveSearchTerm()">
<input type="text" ng-model="searchTerm" />
<input type="submit">
</form>
<ol ng-repeat = "user in users | filter:filterSearch(searchTerm)">
<li class="names"><span>{{$index}}. </span>{{user.name}}</li>
<li class="skills">{{user.skill}}</li>
</ol>
Javascript
var app = angular.module('app', []);
//App.directive('myDirective', function() {});
//App.factory('myService', function() {});
app.controller('MainCtrl', function ($scope) {
$scope.users = [
{
_id: 1,
name: 'frank young',
skill: 'java'
},
{
name: 'jeff qua',
skill: 'javascript'
},
{
name: 'frank yang',
skill: 'python'
},
{
name: 'ethan nam',
skill: 'python'
},
{
name: 'ethan nam',
skill: 'javascript'
},
];
$scope.searchTerm = "";
$scope.listSearchTerms = [];
$scope.filterSearch = function (terms) {
return function (item) {
return terms.length < 1 ? true :
terms.reduce(function (lastresult, term) {
return lastresult + (item.name.indexOf(term) > -1 || item.skill.indexOf(term) > -1);
}, 0) > 0;
}
};
$scope.saveSearchTerm = function () {
$scope.listSearchTerms.push($scope.searchTerm);
$scope.searchTerm = "";
}
});

Ember- Showing models data in view

Im wondering here, how to show models data e.g Organization model>name field in ember view
I tried something like this.
organization VIEW
OrganizationObserver : function(){
var organizationModel = this.get('controller.organizations');
//this.OrganizationComputedProperty(organizationModel);
console.log(organizationModel);
}.observes('controller.organizations').on('init'),
OrganizationComputedProperty: function(){
console.log("herrro");
}.property('organization'),
Model
var Organization = DS.Model.extend({
name: DS.attr('string'),
address: DS.belongsTo('agents/address')
});
// Initial data for Organization model, only applies when using
// FixtureAdapter
Organization.FIXTURES = [
{
id: 1,
name: 'TU',
address: 1,
},
{
id: 2,
name: 'TLU',
address: 2,
}
];
Main hbs
{{#each personFormCount}}
{{view 'organization'}}
{{/each}}
Controller
personFormCount: [{id: 1}, {id: 2}]
But i know that's wrong, because they watch for change behaviours which don't take place in model..
Cheers,
Kristjan
Since i was capable of getting model to my view by this.get('controller.organizations')
Which is defined in route
controller.set('organizations', this.store.findAll('agents/organization'));
I looked at the select once again
{{view Ember.Select
contentBinding="organizations"
optionValuePath="content.id"
optionLabelPath="content.name"
selectionBinding="selectedAgent"
class="form-control"
}}
And i just added controller.organizations to contentBinding
{{view Ember.Select
contentBinding="controller.organizations"
optionValuePath="content.id"
optionLabelPath="content.name"
selectionBinding="view.selectedAgent"
class="form-control"
}}

ember {{input}} helper not working

I can't for the life of me figure out why this won't work. Maybe it's obvious, but I've been staring at it too long.
I want the {{input}} pre-populated with the value of Title, the label gets filled in correctly...
<ul>
{{#each}}
<li>
{{input type="text" value=Title }}
<label>{{Title}}</label>
</li>
{{/each}}
</ul>
here's a Gist
Here's the javascript:
window.App = Ember.Application.create({
LOG_TRANSITIONS: true
});
App.ApplicationAdapter = DS.FixtureAdapter.extend();
App.Router.map(function () {
this.resource('Kids', { path: '/' });
});
App.KidsRoute = Ember.Route.extend({
model: function () {
return this.store.find('Kid');
}
});
App.Kid = DS.Model.extend({
Title: DS.attr('string'),
Age: DS.attr('number')
});
App.Kid.FIXTURES = [
{
id: 0,
Age: 5,
Title: "Joe"
},
{
id: 1,
Age: 9,
Title: "Max"
}
];
There seems to be a little bug with {{input}}. The problem was that title is capitalized. I got it to work in this bin. I would recommend to start your attribute names always with a small letter. This is some kind of convention. Most often you will encounter this style opposed to yours.
These are the changes i made to get it to work:
1 - add an alias to title, which is not capitalized:
App.Kid = DS.Model.extend({
Title: DS.attr('string'),
Age: DS.attr('number'),
title : Ember.computed.alias("Title")
});
2 - use the uncapitalited version with the helper:
{{input type="text" value=title }}

{{#each model}} is not listing the models

I'm trying to display the names of each department. I handmade a 'department' model based off of another model i made that does work. Despite them being identical, #each will not loop through the 'departments' and list them.
departments.hbs >
{{#each model}}
<tr>
<td>
{{#linkTo 'department' this}}{{this.departmentName}}{{/linkTo}}
</td>
<td>{{this.departmentName}}</td>
</tr>
{{/each}}
No errors. It just doesn't list the departments.
VpcYeoman.DepartmentsView = Ember.View.extend({
templateName: 'departments'});
VpcYeoman.DepartmentView = Ember.View.extend({
templateName: 'department'
});
VpcYeoman.DepartmentsController = Ember.ObjectController.extend({
// Implement your controller here.
});
VpcYeoman.Department = DS.Model.extend({
departmentName: DS.attr('string'),
departmentMembers: DS.attr('string')
});
VpcYeoman.Department.reopen({
// certainly I'm duplicating something that exists elsewhere...
attributes: function(){
var attrs = [];
var model = this;
Ember.$.each(Ember.A(Ember.keys(this.get('data'))), function(idx, key){
var pair = { key: key, value: model.get(key) };
attrs.push(pair);
});
return attrs;
}.property()
});
VpcYeoman.Department.FIXTURES = [
{
id: 0,
departmentName: "Sickness",
departmentMembers: "61"
},
{
id: 1,
departmentName: "Health",
departmentMembers: "69"
}
];
'department/#/' DOES work. Why is {{#each model}} not able to find the list of departments?
EDIT:
VpcYeoman.DepartmentsController = Ember.ArrayController.extend({
// Implement your controller here.
});
Upon entering {{log model}} before the {{#each model)) loop, I get this response:
[nextObject: function, firstObject: undefined, lastObject: undefined, contains: function, getEach: function…]
__ember1386699686611_meta: Meta
length: 0
__proto__: Array[0]
VpcYeoman.DepartmentsRoute = Ember.Route.extend({
renderTemplate: function() {
this.render();
}
});
VpcYeoman.DepartmentRoute = Ember.Route.extend({});
You need to declare a DepartmentsRoute with the following:
VpcYeoman.DepartmentsRoute = Ember.Route.extend({
model: function() {
return this.store.find('department');
}
});
DepartmentsController should probably be an ArrayController, and you can view the model in the console to validate it has something using ((log model)) before your each
You need to implement a model hook, returning the departments
VpcYeoman.DepartmentsRoute = Ember.Route.extend({
model: function(){
return this.store.find('department');
},
renderTemplate: function() {
this.render();
}
});
the department route is guessing based on the route name and implementing the default model hook.

How do I loop through each record in my data model in a template?

I have a model setup with Ember fixtures. My model is like the following:
App.Question = DS.Model.extend({
isCompleted: DS.attr('boolean'),
question_top: DS.attr('string'),
question_bottom: DS.attr('string'),
etc......
});
My fixtures (the actual data) is like the following:
App.Question.FIXTURES = [
{
id: 1
},
{
id: 2
}
];
I want to create a unordered list in my template that shows a "li" item for each record in my Fixtures. I think I need to use the {{#each question}} syntax but when I do {{#each question}}, it doesn't work.
How do I loop through my Fixtures data to create a unordered list, with one list item for each record in my Fixtures data?
Probably your question property doesn't exist in your controller. If you are doing:
App.QuestionRoute = Ember.Route.extend({
model: function() {
return this.store.find('question');
}
});
You can use:
<h2>Questions:</h2>
<ul>
{{#each model}}
<li>{{question_top}}</li>
{{/each}}
</ul>
Give a look in that fiddle http://jsfiddle.net/marciojunior/25GHN/
You need to return it to a route's model hook:
http://emberjs.jsbin.com/UGEmEXEy/1/edit
App.IndexRoute = Ember.Route.extend({
model: function() {
return this.store.find('question');
}
});
App.QuestionAdapter = DS.FixtureAdapter;
App.Question = DS.Model.extend({
isCompleted: DS.attr('boolean'),
question_top: DS.attr('string'),
question_bottom: DS.attr('string')
});
App.Question.FIXTURES = [
{
id: 1,
isCompleted: true
},
{
id: 2,
isCompleted: false
}
];

Categories

Resources