Halp!
I'm trying to write a web-crawler in python. The goal is to (eventually) loop through a list of domains, crawl all local-URLs within those domains, and dump all of the HTML content back to my host.
For now, I'm handing the script a single domain (http://www.scrapethissite.com). I've defined a queue, as well as sets for new/processed/local/foreign/broken-URLs. Based on the output, it looks like the script is reading in HTML of the page, grabbing the first local_URL ('https://scrapethissite.com/lessons/'), but failing to process that URL by adding it to the queue.
Ideally, the script would spit out each input URL's output into its own directory, preserving the DOM of the TLD. But I'd be happy just to get the queue working.
Here's my code:
from bs4 import BeautifulSoup
import requests
import requests.exceptions
from collections import deque
from urllib.parse import urlsplit, urlparse
from urllib.request import Request, urlopen
import requests
from html.parser import HTMLParser
import lxml
#set targets
url = 'https://scrapethissite.com'
new_urls = deque(([url]))
processed_urls = set()
local_urls = set()
foreign_urls = set()
broken_urls = set()
#process urls until we exhaust queue
while len(new_urls):
url = new_urls.popleft()
processed_urls.add(url)
print("processing %s..." % url)
try:
response = requests.get(url).text
print(response)
print(new_urls)
except(requests.exceptions.MissingSchema, requests.exceptions.ConnectionError, requests.exceptions.InvalidURL, requests.exceptions.InvalidSchema):
broken_urls.add(url)
print(("this %s failed") % url)
continue
##get base URL to differentiate local and foreign addresses
###not working
print("differentiating addresses...")
parts = urlsplit(url)
base = "{0.netloc}".format(parts)
strip_base = base.replace("www.","")
base_url = "{0.scheme}://{0.netloc}".format(parts)
path = url[:url.rfind('/')+1] if '/' in parts.path else url
#initialize soup
print("initializing soup...")
response = requests.get(url).text
soup = BeautifulSoup(response, 'lxml')
#get links in HTML
for link in soup.find_all('a'):
anchor = link.attrs["href"] if "href" in link.attrs else ''
#scrape page for links
print("scraping links...")
if anchor.startswith('/'):
local_link = base_url + anchor
local_urls.add(local_link)
elif strip_base in anchor:
local_urls.add(anchor)
elif not anchor.startswith('http'):
local_link = path + anchor
local_urls.add(local_link)
else:
foreign_urls.add(anchor)
print(forieng_urls)
print(local_urls)
#to crawl local urls
#...and add them to sets
for i in local_urls:
if not i in new_urls and not i in processed_urls:
new_urls.append(i)
#to crawl all URLs
#for i in local_urls:
#if not link in new_urls and not link in processed_urls:
#new_urls.append(link)
print("new urls: %s" % new_urls)
print("processed urls: %s" % processed_urls)
print("broken urls: %s" % broken_urls)
And here's the output:
(base) $ crawler % python3 bsoup_crawl.py
processing https://scrapethissite.com...
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Scrape This Site | A public sandbox for learning web scraping</title>
<link rel="icon" type="image/png" href="/static/images/scraper-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A public sandbox for learning web scraping">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="/static/css/styles.css">
</head>
<body>
<nav id="site-nav">
<div class="container">
<div class="col-md-12">
<ul class="nav nav-tabs">
<li id="nav-homepage">
<a href="/" class="nav-link hidden-sm hidden-xs">
<img src="/static/images/scraper-icon.png" id="nav-logo">
Scrape This Site
</a>
</li>
<li id="nav-sandbox">
<a href="/pages/" class="nav-link">
<i class="glyphicon glyphicon-console hidden-sm hidden-xs"></i>
Sandbox
</a>
</li>
<li id="nav-lessons">
<a href="/lessons/" class="nav-link">
<i class="glyphicon glyphicon-education hidden-sm hidden-xs"></i>
Lessons
</a>
</li>
<li id="nav-faq">
<a href="/faq/" class="nav-link">
<i class="glyphicon glyphicon-flag hidden-sm hidden-xs"></i>
FAQ
</a>
</li>
<li id="nav-login" class="pull-right">
<a href="/login/" class="nav-link">
Login
</a>
</li>
</ul>
</div>
</div>
</nav>
<script type="text/javascript">
var path = document.location.pathname;
var tab = undefined;
if (path === "/"){
tab = document.querySelector("#nav-homepage");
} else if (path.indexOf("/faq/") === 0){
tab = document.querySelector("#nav-faq");
} else if (path.indexOf("/lessons/") === 0){
tab = document.querySelector("#nav-lessons");
} else if (path.indexOf("/pages/") === 0) {
tab = document.querySelector("#nav-sandbox");
} else if (path.indexOf("/login/") === 0) {
tab = document.querySelector("#nav-login");
}
tab.classList.add("active")
</script>
<div id="homepage">
<section id="hero">
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<img src="/static/images/scraper-icon.png" id="townhall-logo" />
<h1>
Scrape This Site
</h1>
<p class="lead">
The internet's best resource for learning <strong>web scraping</strong>.
</p>
<br><br><br>
<a href="/pages/" class="btn btn-lg btn-default" />Explore Sandbox</a>
<a href="/lessons/" class="btn btn-lg btn-primary" />
<i class="glyphicon glyphicon-education"></i>
Begin Lessons →
</a>
</div><!--.col-->
</div><!--.row-->
</div><!--.container-->
</section>
</div>
<section id="footer">
<div class="container">
<div class="row">
<div class="col-md-12 text-center text-muted">
Lessons and Videos © Hartley Brody 2018
</div><!--.col-->
</div><!--.row-->
</div><!--.container-->
</section>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha256-Sk3nkD6mLTMOF0EOpNtsIry+s1CsaqQC1rVLTAy+0yc= sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pnotify/2.1.0/pnotify.core.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/pnotify/2.1.0/pnotify.core.min.css" rel="stylesheet" type="text/css">
<!-- pnotify messages -->
<script type="text/javascript">
PNotify.prototype.options.styling = "bootstrap3";
$(function(){
});
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
<!-- golbal video controls -->
<script type="text/javascript">
$("video").hover(function() {
$(this).prop("controls", true);
}, function() {
$(this).prop("controls", false);
});
$("video").click(function() {
if( this.paused){
this.play();
}
else {
this.pause();
}
});
</script>
<!-- insert google analytics here -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-41551755-8', 'auto');
ga('send', 'pageview');
</script>
<!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
document,'script','https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '764287443701341');
fbq('track', "PageView");</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=764287443701341&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->
<!-- Google Code for Remarketing Tag -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 950945448;
var google_custom_params = window.google_tag_params;
var google_remarketing_only = true;
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//googleads.g.doubleclick.net/pagead/viewthroughconversion/950945448/?guid=ON&script=0"/>
</div>
</noscript>
<!-- Global site tag (gtag.js) - Google AdWords: 950945448 -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-950945448"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'AW-950945448');
</script>
</html>
deque([])
differentiating addresses...
initializing soup...
scraping links...
new urls: deque(['https://scrapethissite.com/lessons/', <a class="btn btn-lg btn-primary" href="/lessons/"></a>])
processed urls: {'https://scrapethissite.com'}
broken urls: set()
Related
Rebuilding a previous project and trying to learn node and CRUD functions with mongodb. i have a connection to my database and a separate server.js file with mongoose and express.
in server.js the server runs correctly im just not sure how to view my data on the page
here is my code:
server.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const ejs = require('ejs');
app.set('view engine', 'ejs');
mongoose.connect("mongodb connection string here");
const recipeSchema = {
title: String,
ingredients: Array,
instructions: String,
picture_link: String
}
const Recipe = mongoose.model('Recipe', recipeSchema);
app.use(express.static('public'));
app.get('/', function(req, res) {
res.render('index', {});
});
app.get('viewrecipes', function(req, res){
Recipe.find({}, function(err, recipes) {
res.render('viewrecipes', {
recipesList: recipes
})
})
});
app.listen(4000, function() {
console.log('server is running');
});
viewrecipes.ejs file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css" type="text/css">
<title>Document</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light ">
<div class="container-fluid">
<a class="navbar-brand" href="/">Recipe Fix!</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-end" id="navbarNav">
<ul class="navbar-nav ">
<li class="nav-item">
<a class="nav-link" id="submit-recipe" href="#">Submit a Recipe</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/viewrecipes">View Recipes</a>
</li>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search for recipes" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</ul>
</div>
</div>
</nav>
<%recipesList.forEach(recipe => {%>
<div class="card" style="width: 18rem;">
<img src="..." class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title"><%= recipe.title %></h5>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item"><%= recipe.ingredients %></li>
</ul>
<div class="card-body">
<%= recipe.instructions %>
</div>
</div>
<%})%>
<script src="core.js"></script>
<script src="server.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>
The above query has been solved but there is a new problem. I am using materialize.css for using modal and slider. Now whenever I go to the adminpage they are not working. I just show a grey screen in the slider and the modal is not getting activated. The js initialization is in my index.html which i am sharing below and the admin page which contains the modal and slider code.
index.html-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See
https://developers.google.com/web/fundamentals/engage-and-retain/web-app-
manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root">
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-
2.1.1.min.js">
</script>
<script type="text/javascript"src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js">
</script>
<script>
$(document).ready(function () {
// the "href " attribute of .modal-trigger must specify the modal ID that wants to be triggered
$(".sidenav-trigger").sideNav();
$(".carousel").carousel();
$(".modal-trigger").leanModal();
$('.slider').slider({ full_width: true });
})
</script>
</body>
</html>
import React, { Component } from "react";
import { Link } from "react-router-dom";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import BillForm from "./BillForm";
import { addBill } from "../actions/Bill";
import AddBillerForm from "./AddBillerForm";
import { addBiller } from "../actions/Biller";
import Image from "../images/main.jpg";
import Image3 from "../images/Photo3.jpg";
import Footer from "./Footer";
import { fetchAdmin, adminLogout } from "../actions/Admin";
import Slider from "./Slider";
class AdminPage extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.dispatch(fetchAdmin());
}
onLogout() {
this.props.dispatch(adminLogout());
this.props.history.push("/");
}
render() {
if (this.props.Admin.length < 1) {
return <div>No data</div>;
}
if (this.props.Admin.length >= 1) {
if (!this.props.Admin[0].Login) {
return <div>Not logged in as admin</div>;
}
if (this.props.Admin[0].Login) {
return (
<div>
<nav>
<div className="nav-wrapper">
<Link to="/adminpage">
<h3 className="left brand-logo">Bill Payment</h3>
</Link>
<ul className="right">
<li>
<Link className="btn-small" to="viewbiller">
View Biller
</Link>
</li>
<li>
<Link className="btn-small modal-trigger" to="#modal2">
Add Biller
</Link>
</li>
<li>
<Link className="btn-small" to="/generatedbills">
Generated Bills List
</Link>
</li>
<li>
<Link className="btn-small modal-trigger" to="#modal1">
Generate New Bill
</Link>
</li>
<li>
<button className="btn-small btn-flat teal">
Top Bill Payments
</button>
</li>
<li>
<button
className="btn-small btn-flat white-text"
onClick={e => this.onLogout()}
>
Logout
</button>
</li>
</ul>
</div>
</nav>
<div id="modal1" className="modal">
<div className="modal-content">
<div>
<p>Generate New Bill for User</p>
<BillForm
onSubmit={(bill = {}) => {
this.props.dispatch(addBill(bill));
this.props.history.push("/adminpage");
}}
/>
</div>
</div>
<div className="modal-footer red lighten-2">
<Link
to="#!"
className=" modal-action modal-close waves-effect waves-green
btn-flat"
>
Close
</Link>
</div>
</div>
<div id="modal2" className="modal">
<div className="modal-content">
<div className="">
<div className="green white-text">
<h3>Add Biller</h3>
</div>
<AddBillerForm
onSubmit={(biller = {}) => {
this.props.dispatch(addBiller(biller));
}}
/>
</div>
</div>
<div className="modal-footer red lighten-2">
<a
href="#!"
className=" modal-action modal-close waves-effect waves-green
btn-flat"
>
Close
</a>
</div>
</div>
<div>
<Slider />
</div>
<Footer />
</div>
);
}
}
}
}
const mapStateToProps = state => {
return { Admin: state.Admin };
};
export default withRouter(connect(mapStateToProps)(AdminPage));
All of your return statement are in if-statements at the moment. React always expects a return statement in the render. When none of your if-statement return true you don't have any return statement. You should add a return statement at the end of your component which returns an empty jsx element or a loading icon.
Try adding the following code on the end of your render method(should be line 127, not 100% sure): return <span> ...loading </span>
I am creating a website using MVC5 (we do for all our websites here) and I am trying to integrate the FlexSlider (found here: https://woocommerce.com/flexslider/) into one of my pages.
I can't seem to get it working, the page just displays nothing, yet it appears in the 'Inspect Element' with each image as being 0x0 px.
HTML:
<div class="flexslider" data-controlnav="thumbnails">
<ul class="slides">
#if (Model.CDSContent != null)
{
foreach (var item in Model.CDSContent)
{
<li>
<a href="#">
<img src="#Html.Raw(item["newsimage"])" alt="Slide 2">
<div class="flex-caption">newstitle</div>
</a>
</li>
}
}
</ul>
</div>
I also have the JS and CSS linked:
<link rel="stylesheet" type="text/css" href="http://flexslider.woothemes.com/css/flexslider.css">
<link rel="stylesheet" type="text/css" href="http://lab.mattvarone.com/projects/jquery/totop/css/ui.totop.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type='text/javascript' src="http://flexslider.woothemes.com/js/jquery.flexslider.js"></script>
<script type='text/javascript' src="http://flexslider.woothemes.com/js/jquery.easing.js"></script>
<script type='text/javascript' src="http://flexslider.woothemes.com/js/jquery.mousewheel.js"></script>
<script type='text/javascript' src="http://lab.mattvarone.com/projects/jquery/totop/js/jquery.ui.totop.js"></script>
Of course its a little bit difficult to say why your code is not working.
Have you checked what #Html.Raw(item["newsimage"]) returns ?
But...
You could use a carousel that runs on bootstrap.
The code below i made is to scan a folder for images and then i send them to the view with a viewbag.
--Controller code Start--
var GetSliderImaged = Directory.EnumerateFiles(Server.MapPath("~/Content/SlideShowIndexPage")).Select(fn => Path.GetFileName(fn));
ViewBag.Sliderimages = GetSliderImaged;
--Controller code End--
--View code Start--
<div id="myCarousel" class="carousel slide MTop10 BRadius10 unselectable" data-ride="carousel" data-interval="6000">
<ol class="carousel-indicators" style="margin-bottom: 0px;">
#{
var ii = 0;
foreach (var image in ViewBag.Sliderimages)
{
if (ii == 0)
{
<li data-target="#myCarousel" data-slide-to="#ii" class="active"></li>
}
else
{
<li data-target="#myCarousel" data-slide-to="#ii"></li>
}
ii++;
}
}
</ol>
<div class="carousel-inner " role="listbox">
#{
var i = 0;
foreach (var image in ViewBag.Sliderimages)
{
if (i == 0)
{
<div class="item active">
<img src="~/Content/SlideShowIndexPage/#image" alt="#image" title="#image" class="img-responsive AWIndexPageSlideImage" />
<div class="carousel-caption">
</div>
</div>
i++;
}
else
{
<div class="item">
<img src="~/Content/SlideShowIndexPage/#image" alt="#image" title="#image" class="img-responsive AWIndexPageSlideImage" />
<div class="carousel-caption">
</div>
</div>
}
}
}
</div>
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
--View code End--
Just so you know .. the code is not complete but its works for sure if there are images "It does not check if there are no images in the viewbag etc"
But for sure that will be easy to make it yourself.
Just like in the question: how can I use Passport without redirecting user to the /signin or /home when he fails his authentication?
To login user has to click on "login" button, a modal will pop up, he fills the data. If he succeeds he is redirected to the homepage. But if he isn't I want to show him the flash message in the same modal without redirecting. It kinda works because if you fail to login and click "login" again the error message will be shown. But I don't want to force users to constantly click it to check what went wrong.
They should fail, see the error, fill in new data and click submit again.
home.server.route.js:
var user = require(__dirroot + '/app/controllers/user.server.controller.js')
var passport = require('passport')
module.exports = function(app) {
var home = require(__dirroot + '/app/controllers/home.server.controller.js')
app.get('/', home.render)
app.route('/home/signin')
.get(user.renderSignin)
.post(passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/',
failureFlash: true
}))
}
home.server.controller.js:
exports.render = function(req, res) {
res.render('home', {
title: 'erpeg',
messages: req.flash('error') || req.flash('info'),
srvuser: req.user ? req.user : null,
cltuser: JSON.stringify(req.user)
})
}
home.ejs:
<!doctype>
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="lib/foundation/css/normalize.css">
<link rel="stylesheet" href="lib/foundation/css/foundation.css">
<script src="https://www.google.com/recaptcha/api.js"></script>
<script src="lib/jquery/dist/jquery.min.js"></script>
</head>
<body>
<nav class="top-bar">
<ul class="title-area">
<li class="name">
<h1>
<a href="/">
<%= title %>
</a>
</h1>
</li>
<li class="toggle-topbar menu-icon">
<a href="#">
<span>Menu</span>
</a>
</li>
</ul>
<section class="top-bar-section">
<ul class="right">
<% if (srvuser) { %>
<% if(srvuser.rank == "administrator") { %>
<li>
</li>
<% } %>
<li>
<a href="/profile">
<%= srvuser.fullName %>
</a>
</li>
<li>
wyloguj
</li>
<% } else { %>
<li>
rejestruj
</li>
<li class="active">
zaloguj
</li>
<% } %>
</ul>
</section>
</nav>
<div id="signinModal" class="reveal-modal" data-reveal aria-labelledby="signinTitle" aria-hidden="true" role="dialog">
<% for (var i in messages) { %>
<div data-alert class="alert-box warning">
<p>
<%= messages[i] %>
</p>
×
</div>
<% } %>
<h1 id="signinTitle">logowanie</h1>
<form action="/home/signin", method="post">
<div class="row">
<div class="large-12 columns">
<input type="text" name="username" id="username" placeholder="nazwa użytkownia">
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input type="password" name="password" id="password" placeholder="password">
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input class="button expand" type="submit" value="zaloguj">
</div>
</div>
</form>
</div>
<script src="lib/modernizr/modernizr.js"></script>
<script src="./lib/foundation/js/foundation.min.js"></script>
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular-route/angular-route.min.js"></script>
<script src="lib/angular-resource/angular-resource.min.js"></script>
<script src="/user/user.client.module.js"></script>
<script src="/user/services/authentication.client.service.js"></script>
<script src="/game/game.client.module.js"></script>
<script src="/game/controllers/game.client.controller.js"></script>
<script src="/game/services/game.client.service.js"></script>
<script src="/game/config/game.client.route.js"></script>
<script src="application.js"></script>
</body>
</html>
PS: I had it working with separate pages but since I am changing my template engine from Jade to EJS I thought I will do it more elegantly (inside a modal). Any help?
My slider wont come up on first time navigation of the page. However when I hard refresh the page then it comes up and also if I replace the <div ng-view></div> code with the front.html page content then also the slider starts working. Let me know what I am doing wrong in angular as I believe it is something basic that I am missing.
Following is my layout code -
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>WEBSITE</title>
<link rel="stylesheet" href="assets/css/style.css" />
<link rel="stylesheet" href="assets/css/flexslider.css" type="text/css" media="screen" />
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/jquery.flexslider.js"></script>
<script src="assets/js/angular.js"></script>
<script src="assets/js/angular-route.js"></script>
<script src="controllers/mainController.js"></script>
<script>
jQuery(document).ready(function($) {
jQuery(window).load(function() {
jQuery('.flexslider').flexslider({
animation: "slide"
});
});
});
</script>
</head>
<body ng-controller="mainController">
<header ng-include="'includes/header.html'"></header>
<nav ng-include="'includes/navmenu.html'"></nav>
<div ng-view></div>
<footer ng-include="'includes/footer.html'"></footer>
</body>
</html>
Following is my main controller code -
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'views/pages/front.html',
controller: 'frontCtrl'
})
});
In front.html I have slider code -
<div class="flexslider">
<ul class="slides">
<li>
<img src="assets/images/banner1.jpg">
</li>
<li>
<img src="assets/images/banner2.jpg">
</li>
<li>
<img src="assets/images/banner3.jpg">
</li>
<li>
<img src="assets/images/banner4.jpg">
</li>
</ul>
</div>
EDIT -
If I also write this code in the Firebug console then also slider starts working but not on page load -
jQuery('.flexslider').flexslider();
The event handler attached with jQuery(window).load will run when the page is fully loaded. However, ng-view hasn't loaded your view yet, which means <div class="flexslider"> doesn't exist.
Move the initialization into a directive:
myApp.directive('flexslider', function () {
return {
link: function (scope, element, attrs) {
element.flexslider({
animation: "slide"
});
}
}
});
And use like this:
<div class="flexslider" flexslider>
Demo: http://plnkr.co/edit/aVC9fnRhMkKw3xfpm4No?p=preview