I'm learning ember these days and I encountered a problem with link-to helper. If I use it to create a link for nested route it works fine (if click on the link, "active" class will be added to the element - as described in docs) until I reload the page. When I reload the page the content for nested rouse will be loaded to the {{outlet}} properly but link will lose its "active" class. What am I doing wrong?
JavaScript:
window.App = Ember.Application.create({ rootElement: '#app' });
App.Router.map(function () {
this.resource('notes', { path: '/' }, function () {
this.route('show', { path: '/:note_id' });
});
});
App.NotesRoute = Em.Route.extend({
model: function () {
return App.Note.find();
}
});
App.NotesShowRoute = Em.Route.extend({
model: function (params) {
return App.Note.find(params.note_id);
}
});
App.Note = Em.Object.extend();
App.Note.reopenClass({
find: function(id) {
var notes = [
{
id: 1,
title: 'abc',
text: 'lorem ipsum text 1111111'
},
{
id: 2,
title: 'def',
text: 'lorem ipsum text 2222222'
}
];
return id ? notes[parseInt(id) - 1] : notes;
}
});
HTML:
<div id="app" class="row">
<script type="text/x-handlebars">
<div class="col-md-2">
<h2>Tags</h2>
</div>
{{outlet}}
</script>
</div>
<script type="text/x-handlebars" data-template-name="notes">
<div class="col-md-3">
<h2>Notes</h2>
{{#each}}
{{#link-to 'notes.show' this}}{{title}}{{/link-to}}
{{/each}}
</div>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="notes/show">
<div class="col-md-7">
<h2>{{title}}</h2>
<p>{{text}}</p>
</div>
</script>
When you click a link-to, it passes the object to the new route. So the model lookup isn't called. So both the context of the show route and the linked object refer to the same object. So it will get marked as active.
However, when you refresh the page, you're doing the lookup twice, once in the NotesRoute model (which you loop over with each), and once in the NotesShowRoute model.
Javascript objects are reference types. Two plain javascript objects aren't considered equal, even if their content is the same. e.g. try typing this into your javascript console.
{ one: 1, two: 2} == {one: 1, two: 2}
So the object referred to in the link-to isn't the same as the model of the current route. So the equality check for the link being active won't work.
Quick solution is to stop the find from creating the object every time. e.g.
App.Note.reopenClass({
all: [
{
id: 1,
title: 'abc',
text: 'lorem ipsum text 1111111'
},
{
id: 2,
title: 'def',
text: 'lorem ipsum text 2222222'
}
],
find: function(id) {
return id ? this.all[parseInt(id) - 1] : this.all;
}
});
Another options is to roll some sort of identity map for your objects. Here is a blog post doing a much better example than I can of explaining it.
Note I haven't actually tested that code because I'm too lazy to create a jsbin. But let me know if it doesn't work.
Related
I'm trying create a follow button on list items in Vue. My strategy is to grab the value of a particular list item property and store it in the data object. Then use this value in a method to add it to an array in my database.
<div v-for="result in results" :key="result.symbol">
{{ result.name }}
<button #click="followStock">+follow</button>
</div>
I'm not sure how to get the value of result.symbol "into" the button element to set the value symbol in the data object below.
<script>
export default {
data() {
return {
results: [ // this is populated by an api call
{
currency: "USD"
exchangeShortName: "NYSE"
name: "International Game Technology PLC"
stockExchange: "NYSE"
symbol: "IGT"
},
{...},
...
],
symbol: "",
};
},
followStock() {
// add this.symbol to database array
},
},
};
</script>
I'm guessing there might be an easier strategy I'm overlooking as I'm still new to Vue, so any other solution that essentially allows me to fire off the value of result.symbol from any rendered result to my database would be awesome.
You can just pass the result as a parameter to your method.
<div v-for="result in results" :key="result.symbol">
{{ result.name }}
<button #click="followStock(result)">+follow</button>
</div>
And in your method:
methods: {
followStock(result) {
// do something with result
console.log({result});
let symbol = result.symbol;
},
}
P.S I didn't see you put your followStock() inside a methods object, but I did so in the example. https://v2.vuejs.org/v2/api/#methods
Write directly as a function call.
The vue compiler will turn followStock(result.symbol) into function(event) {followStock(result.symbol)}.
new Vue({
el: '#app',
data() {
return {
results: [
{
name: "International Game Technology PLC",
symbol: "IGT"
},
{
name: "A name",
symbol: "A symbol"
}
]
};
},
methods: {
followStock(symbol) {
console.log(symbol)
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="result in results" :key="result.symbol">
{{ result.name }}
<button #click="followStock(result.symbol)">+follow</button>
</div>
</div>
As Nazaire mentioned you can access the results anywhere inside the child elements when using v-for.
(it works like a normal for-loop)
It's not only limited to the corresponding element (the element in which you do v-for)
<div v-for="result in results" :key="result.symbol">
{{ result.name }}
<button #click="followStock(result.symbol)">+follow</button>
</div>
followStock(symbol){
// you can now add symbol to db
}
SUMMARYI have a list of brands and a list of products. I am using an ng-repeat to show the list of brands, and an ng-repeat with a filter to show the list of products within their respective brands. I want each brand and each product to have a button that shows more about that brand/product. All of these buttons should use the same function on the controller.
PROBLEMThe button that shows more about the brand also shows more about each of that brand's products, UNLESS (this is the weird part to me) I click the button of a product within that brand first, in which case it will work correctly.
CODEPlease see the Plunker here, and note that when you click on 'show type' on a brand, it also shows all the types of the products within that brand: http://plnkr.co/edit/gFnq3O3f0YYmBAB6dcwe?p=preview
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="MyController as vm">
<div ng-repeat="brand in brands">
<h1>
{{brand.name}}
</h1>
<button ng-click="showType(brand)">
Show Brand Type
</button>
<div ng-show="show">
{{brand.type}}
</div>
<div ng-repeat="product in products
| filter:filterProducts(brand.name)">
<h2>
{{product.name}}
</h2>
<button ng-click="showType(product)">
Show Product Type
</button>
<div ng-show="show">
{{product.type}}
</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="script.js"></script>
</body>
</html>
JAVASCRIPT
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.brands = [{
name: 'Kewl',
type: 'Cereal'
}, {
name: 'Joku',
type: 'Toy'
}, {
name: 'Loko',
type: 'Couch'
}]
$scope.products = [{
name: 'Kewlio',
type: 'Sugar Cereal',
brand: 'Kewl'
}, {
name: 'Kewliano',
type: 'Healthy Cereal',
brand: 'Kewl'
}, {
name: 'Jokurino',
type: 'Rattle',
brand: 'Joku'
}, {
name: 'Lokonoko',
type: 'Recliner',
brand: 'Loko'
}, {
name: 'Lokoboko',
type: 'Love Seat',
brand: 'Loko'
}]
$scope.showType = function(item) {
this.show = !this.show;
}
$scope.filterProducts = function(brand) {
return function(value) {
if(brand) {
return value.brand === brand;
} else {
return true;
}
}
}
});
IMPORTANT NOTE: I realize I could add an attribute to the object (brand.show) and pass the object into the function, then change that attribute to true/false, but I don't want to do this because in my actual application, the button will show a form that edits the brand/product and submits the info to Firebase, and I don't want the object to have a 'show' attribute on it. I would rather not have to delete the 'show' attribute every time I want to edit the info in Firebase.
ng-repeat directive create own scope, when you do
this.show = !this.show
you create/change show property in current scope, if click brand button - for brand scope, that global for product, and when click in product button - for scope concrete product.
To avoid this, you should create this property before clicking button, for example with ng-init, like
ng-init="show=false;"
on element with `ng-repeat" directive
Sample
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.brands = [{
name: 'Kewl',
type: 'Cereal'
}, {
name: 'Joku',
type: 'Toy'
}, {
name: 'Loko',
type: 'Couch'
}]
$scope.products = [{
name: 'Kewlio',
type: 'Sugar Cereal',
brand: 'Kewl'
}, {
name: 'Kewliano',
type: 'Healthy Cereal',
brand: 'Kewl'
}, {
name: 'Jokurino',
type: 'Rattle',
brand: 'Joku'
}, {
name: 'Lokonoko',
type: 'Recliner',
brand: 'Loko'
}, {
name: 'Lokoboko',
type: 'Love Seat',
brand: 'Loko'
}]
$scope.showType = function(item) {
this.show = !this.show;
}
$scope.filterProducts = function(brand) {
return function(value) {
if (brand) {
return value.brand === brand;
} else {
return true;
}
}
}
});
/* Styles go here */
h1 {
font-family: impact;
}
h2 {
font-family: arial;
color: blue;
margin-bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<div ng-app="myApp">
<div ng-controller="MyController as vm">
<div ng-repeat="brand in brands" ng-init="show=false">
<h1>
{{brand.name}}
</h1>
<button ng-click="showType(brand)">
Show Brand Type
</button>
<div ng-show="show">
{{brand.type}}
</div>
<div ng-repeat="product in products
| filter:filterProducts(brand.name)" ng-init="show=false">
<h2>
{{product.name}}
</h2>
<button ng-click="showType(product)">
Show Product Type
</button>
<div ng-show="show">
{{product.type}}
</div>
</div>
</div>
</div>
</div>
The easiest fix for this, if you don't mind putting temporary properties in your data is the following changes:
<div ng-show="product.show">
{{product.type}}
</div>
and
<div ng-show="brand.show">
{{brand.type}}
</div>
and then in your controller
$scope.showType = function(item) {
item.show = !item.show;
}
Alternatively, if you don't want to touch the object properties, you can create an $scope.shownTypes array and have your click either push the object into or remove the object from the shown array. THen you can check for the object's existence in the array and show or not show the type appropriately. Let me know if you need a sample of that.
Your show boolean attribute same for whole tree (is in same scope). Using angular directive with child scope scope:true in ng-repeat helps to isolate each show property. I have forked your plunker code:
http://plnkr.co/edit/cMSvyfeCQOnTKG8F4l55?p=preview
Here is my dilemma. I'm currently loading my categories using a static variable onto the 'category' page. Everything loads and the links are clickable but when a user clicks on the category. The 'categoryPage' won't load the respective images that belong to that category. Here is my code.
categoryPage HTML:
<template name="categoryPage">
<div class="text-center light-container" id="home-section">
<h1>{{categoryName}}</h1>
<hr/>
<div class="row">
{{#each categoryGifs}}
<a href="{{pathFor 'gif'}}">
<img class="freezeframe gifs" data-id="{{_id}}" src="{{image}}"/>
</a>
{{/each}}
</div>
</div>
</template>
categoryPage JS:
Template.categoryPage.helpers({
// Load 16 most recent ones
// When down arrow is click load another 16 more gifs
'categoryName': function(){
var category = this.params.category;
return category;
},
'categoryGifs': function() {
var category = this.params.category;
console.log(category);
return GifsCollection.find({category: category}, {fields: {_id: 1, image: 1, category: 1} });
}
});
Router JS:
Router.route('/categories', {
name: 'categories',
template: 'categories',
fastRender: true
});
Router.route('/categories/:category', {
name: 'categoryPage',
template: 'categoryPage',
data: function(){
var category = this.params.category;
return GifsCollection.find({category: category});
},
fastRender: true
});
in 'categoryGifs': function(), change
var category = this.params.category;
with:
var category = Router.current().params.category;
here is the working code:
http://meteorpad.com/pad/AdRS8mfyHsZjA2Rvp/Leaderboard
So I've used ng-repeat to create a list of all my songs in an album (refer to this question I asked earlier)
So what I am trying to do now is make it so when a user clicks an item from the list, it plays the refered track. This is my app:
enitoniApp.controller('musicItems', ['$scope', function ($scope) {
$scope.ngplaySong = function (ref, name) {
playSong(ref, name)
}
$scope.albums = [
{
name: 'Over The Mountains',
price: 0,
tracks: [
{
name: 'Over The Mountains',
ref: 'otm',
released: 0,
},
{
name: '!C3',
ref: 'ice',
released: 0,
},
{
name: 'Dark Clouds',
ref: 'clouds',
released: 0
},
{
name: 'Fog',
ref: 'fog',
released: 0
}
]
},
{
name: 'test-album',
price: 5000,
tracks: [
{
name: 'test',
ref: 'null'
},
]
}
]
}]);
As you can see, I'm trying to call a regular function using ng-click. This regular function (playSong()) is inside the code for my player, and it plays a track based on the reference id.
snippet from player.js:
/** Play single song **/
function playSong(ref, name) {
showPlayer();
clearPlaylist()
playlistPosition = 0;
addToPlaylist(ref, name, 'play')
}
So I have this in my html:
<li ng-repeat="album in albums">
<div class="info">
<p>{{album.name}}</p>
<p>{{album.price | currency}}</p>
</div>
<ul>
<li ng-animate="grid-fade" ng-repeat="track in album.tracks">
<div class="grid-item" ng-click="ngplaySong('{{track.ref}}','{{track.name}}')">
<div class="cover">
<img ng-src="/img/covers/art_{{track.ref}}.png" alt="">
</div>
<div class="info">
<p>{{track.name}}</p>
<p>{{track.released}}</p>
</div>
</div>
</li>
</ul>
</li>
The weird thing is that even though this is rendering correctly:
THIS gets outputted into the console even though the parameters are correct:
Why is it not binding the data when the function gets called, am I missing something here?
I do not think that you need those braces inside your ng-click. Try this:
<div class="grid-item" ng-click="ngplaySong(track.ref, track.name)">
The thing is that you pass an expression to ng-click which is then parsed by Angular and it is smart enough to recognize the variables from current scope. You can read more on Angular expressions here: https://docs.angularjs.org/guide/expression
In fact, there is a very nice and easy example in Angular ng-click documentation which includes accessing a local variable inside the ng-click expression: https://docs.angularjs.org/api/ng/directive/ngClick
I have a list of products where the name is a link to the product's details view. The list of products is the "Results" view
Samsumg
iPhone
When the user clicks on a product, the "Details" template is shown, and the "Results" template is not shown; at least that is the behavior that I want.
I am using the following code to accomplish this behavior, and have the jsFiddle here http://jsfiddle.net/justinnafe/mLf5G/:
<div data-bind="template: displayMode"></div>
<script type="text/html" id="Result">
<ul data-bind="foreach: products">
<li></li>
</ul>
</script>
<script type="text/html" id="Details">
<p data-bind="text: name"></p>
<p data-bind="text: description"></p>
</script>
and the javascript:
var view = {
name: "Result"
};
var initialProducts = [{
name: "Samsumg",
description: "The best phone"
},{
name: "iPhone",
description: "The other best phone"
}];
var viewModel = (function (){
var products = ko.observableArray(initialProducts),
displayMode = ko.observable(view),
switchDisplayMode = function(item){
if (displayMode() == 'Result') {
displayMode({ name: "Details", data: item });
}
else {
displayMode({ name: "Result", data: item });
}
};
return {
products: products,
displayMode: displayMode,
switchDisplayMode: switchDisplayMode
};
})();
ko.applyBindings(viewModel);
I am trying to pass that product to the Details template, but have been unsuccessful. Any clues or tips would be helpful.
I am currently getting a "ReferenceError: products is not defined" error when I click on a link, but not sure how to fix it. Maybe if I fix that error, the switching views will behave as expected.
In your function to switch the template, you are forgetting that your displayMode observable is holding an object - not a string value.
So inside switchDisplayMode, displayMode() = { name: 'Result' }. Switching that to displayMode().name fixes the problem. See updated fiddle