Binding links within an ember helper - javascript

I'm new to ember.js and ember-cli, all has been going well until I just tried to create my first custom helper.
I'm trying to loop through a model, displaying some image thumbnails on multiple rows within the page.
Everything seems to be working fine but I would like to try and bind the links.
Here's my custom helper:
import Ember from "ember";
export default Ember.Handlebars.makeBoundHelper(function(value, options) {
var out = '';
var b = 0;
for (var i=0; i<value.length; i++) {
b++;
if(b === 1){
out += '<div class="row">';
}
out += '<div class="col-md-4 col-sm-6 col-xs-12 center" style="text-align:center;">\
<div class="row center">\
<div class="col-md-12 center">\
<a href="photo/'+value[i]._data.id+'">\
<img class="center" src="'+value[i]._data.thumb_url+'" />\
</a>\
</div>\
</div>\
<div class="row center">\
<div class="col-md-6">'+value[i]._data.status+'</div>\
<div class="col-md-6"></div>\
</div>\
</div>';
if(b === 3){
out += '</div><div class="row"><div class="col-md-12"> </div></div>';
b=0;
}
}
return new Handlebars.SafeString(out);
});
I know that you can't use link-to directly inside a helper so I've been playing around with different options, with no luck.
The most success I had was trying to run link-to manually using something along the lines of:
Ember.Handlebars.helpers.linkTo.call('photo/1', 'photo.index', options);
But this hasn't been working out for me either.
Any tips? I fear I'm probably going about this in completely the wrong way
Edit
An example of the output I'm trying to achieve with a helper
<div class="row">
<div>
<a link><img></a>
</div>
<div>
<a link><img></a>
</div>
<div>
<a link><img></a>
</div>
</div>
<div class="row">
<div>
<a link><img></a>
</div>
<div>
<a link><img></a>
</div>
<div>
<a link><img></a>
</div>
</div>

You should probably create an Ember Component instead of creating a Handlebars helper. With an Ember Component you can use {{#linkTo}} and all the bindings work.
Use the Ember component to create a virtual property rows, where you set the items
of each row; then you can iterate over the rows and items with regular {{#each}} inside of the component template.
The component code would look like this:
App.SampleComponentComponent = Ember.Component.extend({
rows : function() {
var myRows = [];
var elements = this.get('model');
var b = -1;
for(var i = 0; i<elements.length; i++) {
if(i % 2 === 0) {
b++;
myRows[b] = [];
}
myRows[b][i%2] = elements[i];
}
return myRows;
}.property('model'),
});
The component template would look like:
<ul>
{{#each row in rows}}
<li>
<ol>
{{#each item in row}}
<li>{{item}}</li>
{{/each}}
</ol>
</li>
{{/each}}
</ul>
You will have to pass the array of items to the component in the model paramater.
Working example in: http://emberjs.jsbin.com/cowin/3/
The tutorial in http://emberjs.com/guides/components/ should help.

Related

MeteorJS get MongoDB ID in click event

I have the following mongo collection in my MeteorJS app:
//Server side, load all the images
Images = new Mongo.Collection('images');
Meteor.startup(() => {
if(Images.find().count() == 0){
for(var i = 1; i < 23; i++){
Images.insert({
src:"img_"+i+".jpg",
alt:"image "+i
});
}
}
});
I pass that to a template and that works. However, I then want to retrieve the MongoDB id of an image (id that is the primary key/unique ID in MongoDB). I do it with the following code:
//Client side, get the collection and load it to the template
Images = new Mongo.Collection('images');
Template.images.helpers({images:Images.find()});
Template.images.events({
'click .js-del-image': (event) => {
var imageId = event._id;
console.log(imageId);
}
});
This gives me undefined. What am I doing wrong? I thought this._id should give me the MongoDB ID.
For the record, This is my template, the _id attribute gets filled out:
<template name="images">
<div class="row">
{{#each images}}
<div class="col-xs-12 col-md-3" id="{{_id}}">
<div class="thumbnail">
<img class="js-image img-responsive thumbnail-img" src="{{src}}"
alt="{{alt}}" />
<div class="caption">
<p>{{alt}}</p>
<button class="js-del-image btn btn-warning">delete</button>
</div>
</div>
</div> <!-- / col -->
{{/each}}
</div> <!-- / row -->
</template>
The problem was in the declaration of a function:
(event) => { ... } seems to have _id of undefined.
function(event) {...} seems to have the correct context.
See this answer for further information about (event) => {...} vs function(){...} declarations.

How to add divs with some classess to another div (inside each other) in html / javascript

I want to list my products from database by clicking on category in html/view.
Firstly I created it in HTML (static) just to check how this is going to look, and it looks lik this:
Here is my html:
<div class="col-md-8" style="margin-top: -15px;">
<div class="products row">
<div class="col-md-3">
<div class="product-holder">
<img class="img-responsive" src="images/coke.png">
<p class="product-title">
Product no1
</p>
</div>
</div>
<div class="col-md-3">
<div class="product-holder">
<img class="img-responsive" src="images/pepsi.png">
<p class="product-title">
Product no2
</p>
</div>
</div>
<div class="col-md-3">
<div class="product-holder">
<img class="img-responsive" src="images/coffe.png">
<p class="product-title">
Product no3
</p>
</div>
</div>
</div>
</div>
And now I want to create this block dynamically:
<div class="col-md-3">
<div class="product-holder">
<img class="img-responsive" src="images/coffe.png">
<p class="product-title">
Product no N
</p>
</div>
</div>
Here is what I've tried so far:
<script>
function onSelectGroup(Id) {
$.ajax({
method: "GET",
url: "Products/GetProductsByCategoryId",
data: { categoryId: Id }
})
.done(function (response) {
//In response I am getting my products, looping through them to create divs like in code above
for (var i = 0; i < response.length; i++) {
//<div class="col-md-3">
// <div class="article-holder">
// <img class="img-responsive" src="images/picture_not_available_400-300.png">
// <p class="product-title">
// Product no 1
// </p>
// </div>
// </div>
//Trying to append it to my .product class because it's parent of this divs above
$(".products").append('<div class="col-md-3"></div>');
$(".products).appendChild('<div class="article-holder"></div>');
}
})};
</script>
But this is not working unfortunatelly... I tried few another things, but this appendings are not working as expected :/
Thanks guys for any help
Cheers
There are many answers posted for the question which might solve the issue with the javascript code. I am posting a different approach as OP specifically requested for it in the comments.
At times, i do not like to build complex HTML markup in javascript with jQuery ( i afraid i might make typos (missing "" or ' etc..). In that case, i would like to have my action method return a view result (the HTML markup) as the response of my ajax call and i can simply update the DOM with that as needed.
public ActionResult GetProductsByCategoryId(int categoryId)
{
var p = db.Products.Where(a=>a.CategoryId==categoryId).ToList();
return PartialView("ProductList",p);
}
Now i will have a partial view called ProductList.cshtml, which is strongly typed to a list of products and i can loop through the items passed to it and render whatever markup i want.
Here is a simple example where i am rendering a div with css class col-md-3 for each item in the collection passed to it. You can update it to render whatever markup you want to render.
#model List<Product>
#foreach (var item in Model)
{
<div class="col-md-3">
<div class="product-holder">
<img class="img-responsive" src="#item.ImageUrl">
<p class="product-title">
#item.Name
</p>
</div>
</div>
}
Now all i have to do is, call this action method, and use the response to update my DOM. Let's give an Id to the container div which we will update
<div class="col-md-8" >
<div id="product-list" class="products row">
</div>
</div>
Now when the ajax call receives a response from server, update the inner html of the DOM element with Id product-list
$.ajax({
method: "GET",
url: "#Url.Action("GetProductsByCategoryId","Products")",
data: { categoryId: 2345 }
})
.done(function(response) {
$("#product-list").html(response);
}).fail(function(a, a, e) {
alert(e);
});
Keep in mind that, now you are getting a bigger payload (the resulting HTML)
from the server compared to the JSON data. So use this approach as you feel appropriate to do so. With this approach, i can use the C# methods in my partial view (For example, to build the path to an image in a location/ use Html helper methods etc)
I you create the dom element like any string, and append it to the container
function onSelectGroup(Id) {
//In response I am getting my products, looping through them to create divs like in code above
for (var i = 0; i <10; i++) {
let item = `<div class="col-md-3">
<div class="article-holder">
<img class="img-responsive" src="images/picture_not_available_400-300.png">
<p class="product-title">
Product no ${i}
</p>
</div>
</div>`
//Trying to append it to my .product class because it's parent of this divs above
$(".products").append(item);
}
};
onSelectGroup();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-8" style="margin-top: -15px;">
<div class="products row">
<div class="col-md-3">
<div class="product-holder">
<img class="img-responsive" src="images/coke.png">
<p class="product-title">
Product no1
</p>
</div>
</div>
<div class="col-md-3">
<div class="product-holder">
<img class="img-responsive" src="images/pepsi.png">
<p class="product-title">
Product no2
</p>
</div>
</div>
<div class="col-md-3">
<div class="product-holder">
<img class="img-responsive" src="images/coffe.png">
<p class="product-title">
Product no3
</p>
</div>
</div>
</div>
</div>
You can create a new element with jquery and fill it properly
for (var i = 0; i < response.length; i++) {
//<div class="col-md-3">
// <div class="article-holder">
// <img class="img-responsive" src="images/picture_not_available_400-300.png">
// <p class="product-title">
// Product no 1
// </p>
// </div>
// </div>
//Trying to append it to my .product class because it's parent of this divs above
var newelem = $('<div class="col-md-3"></div>');
var artholder = $('<div class="article-holder"></div>');
newelem.append(artholder);
artholder.append(<your-image><your article title>);
}
You was close; all you needed to do was create an element for each item in the results object. I've used test data in the example.
https://jsfiddle.net/tw0vrpyy/
var response = {
item1: {
id: "id1",
title: "title1",
img: "img_src1.jpg"
},
item2: {
id: "id2",
title: "title2",
img: "img_src2.jpg"
}
};
var product = document.getElementsByClassName('response')[0];
Object.keys(response).forEach(function(key) {
var el = '<div class="col-md-3">' +
'<div class="article-holder">' +
'<img class="img-responsive" src="'+ response[key].img +'">' +
'<p class="product-title">' +
response[key].title +
'</p>' +
'</div>' +
'</div>';
product.innerHTML += el;
});

How to loop through JavaScript object in HTML?

I want to loop through a JavaScript object and repeat an html script as many times as the object length.
Here, I have the following in a script tag
<script>
var obj;
ipcRenderer.on('requests-results', (event, hosSchema) => {
obj = hosSchema
})
</script>
obj is an array retrieved from Mongo database as the picture below shows:
and I have the following inside <body> tag:
<div class="row">
<div class="col-md-4 col-sm-4">
<div class="card">
<div class="card-content">
<span class="card-title">.1.</span>
<p>.2.</p>
</div>
<div class="card-action">
.3.
.4.
</div>
</div>
</div>
</div>
How can I loop through obj to repeat the code between <div> tag as many times as obj.length?
I would suggest you to use Handlebars as #Amit mentioned.
first move out the code inside <div id="page-inner"> as below:
<div id="page-inner">
</div>
<script id= "requests-template" type="text/x-handlebars-template">
<div class="row">
{{#each requests}}
<div class="col-md-4 col-sm-4">
<div class="card">
<div class="card-content">
<span class="card-title">{{this.fieldName}}</span>
<p>{{this.fieldName}}</p>
</div>
<div class="card-action">
{{this.fieldName}}
{{this.fieldName}}
</div>
</div>
</div>
{{/each}}
</div>
</script>
Then inside another script page of type text/javascript you create the requests and assigned obj/hosSchema to it as below:
<script type="text/javascript">
var requestInfo = document.getElementById('requests-template').innerHTML;
var template = Handlebars.compile(requestInfo);
var requestData = template({
requests: obj
})
$('#page-inner').html(requestData);
</script>
NOTE: you need handlebars package installed (npm install handlebars --save)
Use templating script like Handlebars.js, Mustache.js or underscore.js.
Check below link for more description.
http://www.creativebloq.com/web-design/templating-engines-9134396
Try this:
var divlist = document.getElementsByTagName['div'];
var duplicate = null;
var rowIndex = -1;
var found = false;
for(var i = 0;i<obj.length;i++)
{
if(!found)
for(var p = 0;p<divlist.length;p++)
{
if(rowIndex != -1 && duplicate != null)
{
//set a Boolean to true and break
found = true;
break;
}
if(divlist[p].className == "col-md-4 col-sm-4")
{
//copy the element
duplicate = divlist[p];
}
else if(divlist[p].className == "row")
{
//identify the row's index
rowIndex = p;
}
}
//append the duplicate
divlist[rowIndex].appendChild(duplicate);
}

angular2 bootstrap dynamic carousel

I have a dynamic images coming from a json and doing *ngFor to loop through the objs and putting it in a carousel using bootstrap carousel, but I want to put a readmore link within the *ngFor so each item will have a read more.
I can't figure out how to do when a user click "readmore" it will scroll to its relative item showing about the image if that makes sense.
<div class="col-sm-4" *ngFor="let journey of Journey">
<div class="journey_block">
<div class="icon-workflow">
<div class="view view-fourth">
<img src="{{ journey.imageName }}" alt="">
<div class="mask">
Read More
</div>
</div>
<h4 class="journey_title">
<a [href]="journey.journey_url" *ngIf="journey.journey_url != 'javascript:;' " class="float-shadow">
{{journey.title}}
</a>
</h4>
</div>
</div>
My attempt is I thought I would then need to do for loop, I have 5 items in total in the json data.
getImg() {
this.http.get('./journey.json')
.map((res:Response) => res.json())
.subscribe(data => {
if(data) {
var jsonObj = JSON.parse(JSON.stringify(data));
this.Journey = jsonObj.journey;
for (var i = 0; i < this.Journey.length; i++) {
var element = this.Journey[i];
this.objCount = element;
console.log(this.objCount);
}
}
});
};
View full html structure of the carousel
Carousel structure
You need to have the index inside of the loop for making the data-slide-to attribute unique. This could be done by the predefined Angular2 value index.
Example
<!-- Angular 2.0 -->
<ul>
<li *ngFor="let item of items; let i = index">
{{i}} {{item}}
</li>
</ul>
In your code:
<div class="col-sm-4" *ngFor="let journey of Journey; let i = index">
<div class="journey_block">
<div class="icon-workflow">
<div class="view view-fourth">
<img src="{{ journey.imageName }}" alt="">
<div class="mask">
Read More
</div>
</div>
<h4 class="journey_title">
<a [href]="journey.journey_url" *ngIf="journey.journey_url != 'javascript:;' " class="float-shadow">
{{journey.title}}
</a>
</h4>
</div>
</div>

AngularJS not filtering products list

I am having an issue with AngularJS filtering my products list. I have done a few console.log queries on my variables and all seem fine. The problem is that the view does not update to show the filtered products.
Filtering works perfectly fine when you enter the search text in the input box but it does not work when clicking on the Category menu items.
I would like to filter the product list by category when the user clicks on the menu item.
Please see my code below and any help or advice is greatly appreciated.
My app.js
myApp.controller('StoreController', function($scope, $filter, storeFactory, cartFactory) {
$scope.cartTotal = 0;
$scope.cartItems = [];
$scope.categories = [];
$scope.counted = 0;
$scope.filteredProducts = {};
//get the products
storeFactory.getProducts(function(results) {
$scope.products = results.products;
$scope.counted = $scope.products.length;
$scope.filteredProducts = results.products;
});
$scope.$watch("search", function(query){
if($scope.filteredProducts.length) {
$scope.filteredProducts = $filter("filter")($scope.products, query);
$scope.counted = $scope.filteredProducts.length;
}
});
$scope.filterProductsByCategory = function(categoryName){
console.log('category filter');
/*$scope.products.forEach(function(o,i){
console.log('filter');
if( o.category_id !== categoryId ){
$scope.filteredProducts.splice(i,1);
console.log('removing');
console.log(o);
}
});*/
$scope.filteredProducts = $filter("filter")($scope.filteredProducts, categoryName);
console.info('the filtered items');
console.log($scope.filteredProducts);
$scope.counted = $scope.filteredProducts.length;
}
$scope.getCategories = function(){
storeFactory.getCategories(function(results){
$scope.categories = results.rows;
});
}
$scope.getCategories();
});
My store.htm
UPDATE :
I removed the extra controller reference and wrapped everything in one div.
<div ng-controller="StoreController">
<!-- the sidebar product menu -->
<div class="block-content collapse in">
<div class="daily" ng-repeat="category in categories | orderBy:'name'">
<div class="accordion-group">
<div ng-click="filterProductsByCategory(category.category_name)" class="accordion-toggle collapsed">{{category.category_name}}</div>
</div>
</div>
</div>
</div>
<!-- Load store items start -->
<div class="label">Showing {{counted}} Product(s)</div>
<div class="row" ng-repeat="product in filteredProducts | orderBy:'product_name'" style="margin-left: 0px; width: 550px;">
<hr></hr>
<div class="span1" style="width: 120px;">
<!-- <a data-toggle="lightbox" href="#carouselLightBox"> -->
<a data-toggle="lightbox" href="#carouselLightBox{{product.product_id}}">
<!--img alt={{ product.product_name }} ng-src="{{product.image}}" src="{{product.image}}" /-->
<img id="tmp" class="" src="images/products/{{product.product_image_filename}}" alt=""></img>
</a>
<div class="lightbox hide fade" id="carouselLightBox{{product.product_id}}" style="display: none;">
<div class='lightbox-content'>
<img src="images/products/{{product.product_image_filename}}" alt="" />
<!--img alt={{ product.product_name }} ng-src="{{product.image}}" src="{{product.image}}" /-->
<button class="btn btn-primary" id="close_lightbox" ng-click="closeBox(product.product_id, $event)">Close</button>
</div>
<style>
#close_lightbox
{
position: absolute;
top: 5px;
right: 5px;
}
</style>
</div>
</div>
<div class="span6" style="width: 330px; margin-bottom: 15px;">
<h5 style="font-size: 14px; font-weight: bold;">{{product.product_name}}</h5>
<p>{{product.product_description }}</p>
<p>Category : {{product.category_name}}</p>
</div>
<div class="span3">
<p class="price">Price : <strong>R{{ product.product_price }}</strong></p>
</div>
</div>
<!-- end of controller -->
</div>
$scope.filteredProducts = {};
//get the products
storeFactory.getProducts(function (results) {
$scope.products = results.products;
$scope.counted = $scope.products.length;
$scope.filteredProducts = results.products;
});
Is results.products an array of objects or an object of objects? Because $filter('filter')($scope.products,query); expects $scope.products to be an array.
$scope.$watch("search", function (query) {
if($scope.filteredProducts.length) {
$scope.filteredProducts = $filter("filter")($scope.products, query);
$scope.counted = $scope.filteredProducts.length;
}
});
Here's what I'm thinking this should look like and you won't need the $watch statement or the filteredProducts array/object, In controller:
$scope.search = '';
$scope.products = [];
$scope.categories = ['category1','category2','category3'];
// assuming that your store function getProducts returns a promise here
storeFactory.getProducts().then(function(results){
$scope.products = results.products; // needs to be an array of product objects
});
$scope.filterProductsByCategory = function(category){
$scope.search = category;
};
Then in your HTML Partial, this is not exactly how your's is, I'm just showing you here in shorter form what is possible:
<button ng-repeat="cat in categories" ng-click="filterProductsByCategory(cat)">{{cat}}</button>
<div class="row" ng-repeat="product in products | filter:search | orderBy:'product_name'">
<!-- Product Information Here -->
</div>
I created a JSFiddle to demonstrate: http://jsfiddle.net/mikeeconroy/QL28C/1/
You can free form search with any term or click a button for a category.
The side bar is using one instance of StoreController, and the main div is using another instance of StoreController. Each instance having its own scope. The should both use the same controller instance: wrap everything inside a div, and use a unique StoreController for this wrapping div.

Categories