$scope.$apply and ng-include - node.js

I'm using a $scope.$apply to trigger the view to update based on a changed variable in the scope. However, I have another line in the html that is an ng-include,
<div data-ng-include data-ng-src="'views/partials/_menubar.html'"></div>
error message
When I remove the ng-include and replace it with a static call there is no error. Here is the template that I'm including as well:
<div class="menu" ng-controller="MenuController">
<div style="display: inline-block">
Hello!
</div>
<ul class="menu_dropdown">
<li class="menu_item">Test1</li>
<li class="menu_item">Test2</li>
<li class="menu_item">Test3</li>
</ul>
</div>
The code for menu controller is
app.controller('MenuController', function($scope) {
});

ng-src is used to allow elements that usually have a src (like anchors or images) to apply the src tag only after angular's digest, not for inclusion of templates in ng-include. See ng-include docs and ng-src docs.
A safe way to specify the src using ng-include would be like this:
<div data-ng-include="src='views/partials/_menubar.html'"></div>
or
<div data-ng-include="'views/partials/_menubar.html'"></div>
If you must have the src separately, it's data-src and not data-ng-src:
<div data-ng-include data-src="'views/partials/_menubar.html'"></div>
see plnkr.
edit: To address your error message.. you'll see that message if you've bound a function to the scope which changes every time it is called.
For example, this will cause such an error:
// controller
$scope.getQuote = function(){
return 'someViewName' + Math.ceil(Math.random() * 10) + '.html';
};
// view
<div data-ng-include="{{getQuote}}"></div>

The problem with ng-include was actually a red herring. The real problem was trying to change the window.history, as seen in the thread here. My guess is because the ng-include directive references $location when it attempts to get resources.

Related

use href tag for different html pages but with same url id in express

i'm trying to switch between home and profile page for same user with click on each button. also except change between home and profile,id should stay the same.
but after click on profile button only id will be changed and it uses profile as id
(i used ejs as format for my views/html pages)
any idea how can i fix it?is that even possible?
there is my nav code:
<nav>
<div class="nav-wrapper teal darken-4">
BAZAART
<ul class="right hide-on-med-and-down">
<li><a class="waves-effect waves-light btn teal lighten-1" href="home"> <i class="material-icons right">home</i> home</a></li>
<li><a class="waves-effect waves-light btn teal lighten-1" href="profile">profile <i class="material-icons right">account_box</i></a></li>
</ul>
</div>
</nav>
homeController:
exports.sendReqParam = (req, res) => {
let userHome = req.params.userHome;
res.render("home", { name: userHome });
// res.send(`This is the homepage for ${userHome}`);
};
exports.respondWithName = (req, res) => {
let paramsName = req.params.myName;
res.render("profile", { name: paramsName });
}
main.js
app.get("/profile/:myName", homeController.respondWithName);
app.get("/", homeController.respondInfo);
app.get("/home/:userHome", homeController.sendReqParam)
I was recently making a blog website, where I write a post and it displays it on the home page. But if we wanted to go to the specific post page, instead of making another separate page for each new post, we made a post.ejs page instead, and later to acces the specific post we simply used something called lodash. I'll show you an example of it, so it makes more sense, and I'll show you the code we used.
So the example is this, I go to the compose.ejs page and I write a random post: title=Post, content=A random lorem ipsum
and lets say we write another post: title=Another post, content=Another random lorem ipsum
Okay so now everytime we write a blog post it sends us to the home page (where we currently are) and it shows the two blogs posts. If we wanted to go to the specific url of the post, we simply write this link localhost:3000/posts/Another post hit enter and it takes us to the second post we wrote.
And this is the code we used inside the app.js:
app.get("/posts/:postName", function(req, res){
const requestedTitle = _.lowerCase(req.params.postName);
posts.forEach(function(post) {
const storedTitle = _.lowerCase(post.title);
if (storedTitle === requestedTitle) {
res.render("post", {title: post.title, content: post.content});
}
});
});
In the app.js code, we see in the app.get /posts/:postName and this is just the name that is going to show in the url, :postName is like a variable and it will store whatever the user writes.
In the second line, we use lodash to rewrite what the user wrote to what we want, for example if the user wrote AnoTheR POst it will automatically change it to another-post, and we store it in a constant called requestedTitle.
Next is a forEach loop on a posts array (where we store every post), and this is just to go throught every post and check the names.
In the 4th line, we are again using lodash for the same thing, but this time arround for the title of each individual post, and storing it in a constant called storedTitle.
And last, an if statement, where if both the names are the same then it will render the post.ejs page, and we just pass down the title and content from the selected post using this code , {title: post.title, content: post.content}.
And this is the code we used inside the post.ejs:
<%- include("partials/header") -%>
<br>
<div class="card">
<h2 class="card-header"> <%= title %> </h2>
<div class="card-body">
<p class="card-text"> <%= content %> </p>
</div>
</div>
<%- include("partials/footer") -%>
As you can see this post.ejs isn't hard to explain, the top and bottom lines where it says include("partials are just the header and footer templates I use, just to save time coding. Whats inside is what the post.ejs will render when it gets called.
I hope it wasn't that confusing, I'm still learning to code and I hope it helps you with what you are looking for. I think this isn't the exact answer for your question, but I think it will help you navigate your way throught.
If you need more explanation or help, this is my instagram: #cemruniversal, I'm always happy to help if I can.
Edit: 30 minutes after original post
I think I found a way it could work, I'll show you a piece of code from the same blog website.
Whenever I want to compose a new post I use this code:
app.get("/compose", function(req, res){
res.render("compose");
});
And obviously there is a form for you to write the post, and after you submit, it sends you to the home page, and saves the post. For that I used this piece of code:
app.post("/compose", function(req, res){
const post = {
title: req.body.postTitle,
content: req.body.postBody
};
posts.push(post);
res.redirect("/");
});
I had an idea for your website, what if when you pressed the Profile button, it renders a specific page on your site, and when you press another button it renders another page. It could work, wouldn't it?
Please try it out and tell me how it went.
I think something like this:
<nav>
<div class="nav-wrapper teal darken-4">
BAZAART
<ul class="right hide-on-med-and-down">
<li><a class="waves-effect waves-light btn teal lighten-1" href="/home"> <i class="material-icons right">home</i> home</a></li>
<li><a class="waves-effect waves-light btn teal lighten-1" href="/profile">profile <i class="material-icons right">account_box</i></a></li>
</ul>
</div>
</nav>

If element hasClass, add another class to its title value

I'm using slick carousel, and once a div is active I want to open the corresponding description.
Problem I'm having is with this code:
if ($('div').hasClass('active')) {
var title = $(this).attr('title');
$('ul li').removeClass('open');
$(title).addClass('open');
}
What I'm trying to achieve:
Once a div gets class 'active', I want to take its title value, and use it as a id link to list element I want to display(add class to).
Here is a FIDDLE.
Use event handling, not class monitoring.
The slick carousel API has events for this, I believe you want to use the afterChange event to act on the active element after it has been made visible.
Check out the docs and examples, especially the section titled "Events" on Slick page: http://kenwheeler.github.io/slick/
And I think you don't want to use title attribute for this because that is for tooltips. I recommend data-* attributes instead. And element IDs should generally start with a letter and not a number (was required in HTML4 and makes life easier when mapping IDs to JavaScript variables; though if you are using HTML5 I think this requirement is no longer in effect).
HTML
<div id="carousel">
<div data-content-id="content1">
Selector 1 </div>
<div data-content-id="content2">
Selector 2 </div>
<div data-content-id="content3">
Selector 3 </div>
</div>
<ul class="content">
<li id="content1">Content 1</li>
<li id="content2">Content 2</li>
<li id="content3">Content 3</li>
</ul>
JavaScript
$('#carousel').on('afterChange', function(event, slick, currentSlide) {
// get the associated content id
var contentId = $(slick.$slides.get(currentSlide)).data("content-id");
if(contentId && contentId.length)
{
var $content = $("#" + contentId);
$(".content>li").removeClass("open"); // hide other content
$content.addClass("open"); // show target content, or whatever...
}
});
I have found a solution:
$('.slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
var contentId= $(slick.$slides.get(currentSlide)).data('content');
if(contentId)
{
$(".content li").removeClass('open');
$('#' + contentId).addClass('open');
}
});
Working fiddle

iron:router syntax Layout

I am using iron router to render a template within meteor framwork, as i was following probably an outdated tutorial, it seems to me there is a change in syntaxes which i could not figure out.
layout.html
<div class="container">
<div class="row">
<div class="span2">
<p>cell</p>
</div>
<div class="span7">
<p>cell</p>
</div>
<div class="span3">
<p>cell</p>
</div>
</div>
</div>
index.js
function.setDefault ('category', null );
Router.configure({
layoutTemplate:'layout',
yieldTemplates:{
'products':{to:'products'},
'cart':{to:'cart'},
'categories':{to:'categories'}
}
});
Router.route(function(){
this.route('/', layout);
this.route('/products',{
data:function(){
Session.set('category',this.params.name);
},
template:'layout',
path:'/:name'
})
});
The following error occurs
unexpected token (1:8)
Where you have Router.route and use this.route in a function, Router.route should read Router.map however this is deprecated in favour of Router.route (without the map wrapper) as below:
Session.setDefault ('category', null );
Router.configure({
layoutTemplate:'layout',
yieldTemplates:{
'products':{to:'products'},
'cart':{to:'cart'},
'categories':{to:'categories'}
}
});
//You will need to declare a template at the least here so it knows what to render to main area
Router.route('/', {template: "template_name");
Router.route('/products/:name',{
onBeforeAction:function(){
Session.set('category',this.params.name);
this.next ();
},
//you don't need this to be layout
//as you are defining a default layout above
//but you will need to specify a template for the main yield area
template:'template_name'
// you don't need to specify path here as it will use '/products'
//if you want to specify a route name use line below
//,name: 'routename'
});
Where url would be /products/product_name
Where template_name is the template you want to render in your main {{> yield}}
In your layout template you need to place the following for your yields wherever you want to display them
{{> yield 'products'}}
{{> yield 'categories'}}
{{> yield 'cart'}}
{{> yield }} //this is the template you specify in template: 'template_name'
(Done from my phone so can't test but can update later if it doesn't work for you)

How to check type of object in Handlebars?

I am currently working on a search bar that lists three types of objects: users, records and locations. Each has its own model and such defined, with corresponding controllers. What I need to do is to check which type of object it is because I need the HTML that renders with it to be different.
{{#each mainUserSearchResults}}
{{#link-to 'user' this.userID}}
<div class="row mainListSeperator" {{action "getapplicantUserID" this target="view"}}>
<img class="applicantsIcon" src="">
<div class="applicantsName">
{{unbound this.firstName}} {{unbound this.lastName}}
</div>
<div class="applicantsTitle">
User
</div>
</div>
{{/link-to}}
{{/each}}
The only issue I am having is that I need it to print this.firstName & this.lastName if it is a user, but I cannot do that for records. For records, I would have to render another property - this.recordID - in the same manner as I did this.firstName. The way to do this would be an if conditional, but I cannot find anything in HandleBars that allows me to check whether the data coming in from mainUserSearchResults is a user or a record.
The mainUserSearchResults is a property in my controller that returns an array of objects: currently it return a concatenated array of user objects and record objects.
Handlebars is a logicless template, so you really can't perform computations, like type-checking. There are some pretty good reasons for this. If it were me, I'd push that responsibility elsewhere, probably all the way to your model, for two reasons:
Any conditionals you put in the DOM are SLOW. The problem only gets compounded when you're on slow devices (most notably, mobile).
Every time you add a new searchable thing, you're going to have to update your templates. Over time, you'll end up with:
{{#if ...}}
...
{{/if}}
{{#if ...}}
...
{{/if}}
{{#if ...}}
...
{{/if}}
{{#if ...}}
...
{{/if}}
Delegate instead. For example, in your User model, add
formattedName: (function() {
return [this.get('firstName'), this.get('lastName')].join(' ');
}).property('firstName', 'lastName')
Do the same for your records and locations.
Then, change your template from
{{unbound this.firstName}} {{unbound this.lastName}}
to
{{unbound this.formattedName}}
Now, if you add new types to your searches, you have a completely generic solution that only needs the model to implement the formattedName property.
Some would would say my suggestion is a bad one, because it mixes the business-logic responsibility of a model with display logic. In this case, I'm guessing you're displaying {{firstName}} {{lastName}} in more than one place, so I think the benefits of keeping your code DRY outweigh moving this to, e.g., a controller. Your call.
Assuming there is some way to easily distinguish between the 2+ types of objects, you can use an if statement and render a different template (or even use a different partial, http://emberjs.com/guides/templates/rendering-with-helpers/)
<script type="text/x-handlebars" data-template-name="index">
<ul>
{{#each item in model}}
<li>
{{#if item.foo}}
{{render 'foo' item}}
{{/if}}
{{#if item.cow}}
{{render 'cow' item}}
{{/if}}
</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars" data-template-name="foo">
I'm a foo: {{foo}}
</script>
<script type="text/x-handlebars" data-template-name="cow">
I'm a cow: {{cow}}
</script>
http://emberjs.jsbin.com/qinilege/1/edit
Or if you need more advanced checking you can use an item controller and add the logic in there
{{#each item in model itemController='checker'}}
<li>
{{#if item.isFooBar}}
{{render 'foo' item.model}}
{{/if}}
{{#if item.isFooBaz}}
{{render 'fooz' item.model}}
{{/if}}
{{#if item.isCow}}
{{render 'cow' item.model}}
{{/if}}
</li>
{{/each}}
App.CheckerController = Em.ObjectController.extend({
isFooBar: Ember.computed.equal('foo', 'bar'),
isCow: Ember.computed.notEmpty('cow'),
isFooBaz: Ember.computed.equal('foo', 'baz')
});
http://emberjs.jsbin.com/qinilege/2/edit

Global search box in angular

I want to implement a search box that changes what it searches based on whichever controller is being used. If you are on the "posts" view it will search the posts api, if you are on the videos view, it searches the videos api. It seems the search box would need its own controller maybe. I'm pretty sure I need to inject a search service into all the model controllers but I'm not exactly sure how to change the url it searches or tie the input to the different controller scopes.
So any ideas how to have a global search box that changes where it searches based on whichever controller is making use of it and tying its state back into a changing view?
To make a resource call dynamic api i would first create two $resources that map to your two endpoints, posts and videos. Then put an ng-change event on your global search that calls a function in your base controller.
This function firsts need to figure out what api to search. Then make the appropriate api call. The important part is in the callback and i think this is what you are looking for.
In the callback you could $broadcast the resp data from your api query. Each of your controllers will be listening for an event with an $on function. The listeners will then populate the correct scope variable with the callback data.
Pseudo below.
Same html layout with ng-change
<html>
<body ng-controller="AppController">
<form>
<label>Search</label>
<input ng-model="global.search" ng-change="apiSearch()" type="text" class="form-control" />
</form>
<div ui-view="posts">
<div ng-controller="PostController">
<p ng-repeat="post in posts | filter: global.search">{{ post.name }}</p>
</div>
</div>
<div ui-view="videos">
<div ng-controller="VideoController">
<p ng-repeat="video in videos | filter: global.search">{{ video.name }}</p>
</div>
</div>
</body>
</html>
AppController
.controller('AppController', function ($scope, PostService, VideoService) {
$scope.apiSearch = function() {
// Determine what service to use. Could look at the current url. Could set value on scope
// every time a controller is hit to know what your current controller is. If you need
// help with this part let me know.
var service = VideoService, eventName = 'video';
if ($rootScope.currentController == 'PostController') {
service = PostService;
eventName = 'post';
}
// Make call to service, service is either PostService or VideoService, based on your logic above.
// This is pseudo, i dont know what your call needs to look like.
service.query({query: $scope.global.search}, function(resp) {
// this is the callback you need to $broadcast the data to the child controllers
$scope.$broadcast(eventName, resp);
});
}
})
Each of your child controllers that display the results.
.controller('PostController', function($scope) {
// anytime an event is broadcasted with "post" as the key, $scope.posts will be populated with the
// callback response from your search api.
$scope.$on('post', function(event, data) {
$scope.posts = data;
});
})
.controller('VideoController', function($scope) {
$scope.$on('video', function(event, data) {
$scope.videos = data;
});
})
Client side filtering.
If you are not looking for anything to crazy that can be achieved in a super simple way for global search. I didnt even know if this would work so i just did a quick test and it does. Obviously this could be solved in a much more detailed and controlled way using services and injecting them where they are needed. But since i don't know excatly what you are looking for i will provide this solution, if you like it, great accept it. If you don't i could probably help you with service injection solution
Quick solution is to have an app wide contoller with $rootScope ng-model. Lets call it global.search.
$rootScope.global = {
search: ''
};
For the app wide search input.
<form>
<label>Search</label>
<input ng-model="global.search" type="text" class="form-control" />
</form>
In separate partials you just need to filter data based on the global.search ng-model. Two examples
<p ng-repeat="post in posts | filter: global.search">{{ post.name }}</p>
Second template with different scope
<p ng-repeat="video in videos | filter: global.search">{{ video.name }}</p>
Note how they both implement | filter: global.search. Whenever global.search changes, any filters in the current view will be changed. So posts will be filtered on the posts view, and videos on the videos view. While still using the same global.search ng-model.
I tested this, it does work. If you need more detail explaining the setup and child controller hierarchy let me know. Here is a quick look at a full template
<html>
<body ng-controller="AppController">
<form>
<label>Search</label>
<input ng-model="global.search" type="text" class="form-control" />
</form>
<div ui-view="posts">
<div ng-controller="PostController">
<p ng-repeat="post in posts | filter: global.search">{{ post.name }}</p>
</div>
</div>
<div ui-view="videos">
<div ng-controller="VideoController">
<p ng-repeat="video in videos | filter: global.search">{{ video.name }}</p>
</div>
</div>
</body>
</html>

Resources