This is my code:
<script type="text/javascript">
$(document).ready(function() {
$("body").ready(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$(".slider").html(data);
}
});
});
});</script>
I want this code to get HTML code from a .txt file and add it in here:
<div class="slider"> <!-- News Slider --> </div>
The txt file contains the following:
<div class="callbacks_container">
<ul class="rslides" id="slider">
<li>
<h2>Zeah</h2>
<h3>New continent, 50% expansion</h3>
</li>
<li>
<h2>Sailing</h2>
<h3>Sail around the world</h3>
</li>
<li>
<h2>2016</h2>
<h3>Christmas event coming to an end</h3>
</li>
</ul>
</div>
The function above doesn't work and I can't find a way to fix this.
You missed a few braces at the end and the URL should be /helloworld.txt
The / is importamt
I suggest using syntax highlighting.
<script type="text/javascript">
$(document).ready(function() {
$("body").ready(function() {
$.ajax({
url : "/helloworld.txt",
dataType: "text",
success : function (data) {
console.log("executed");
$(".slider").html(data);
}
});
})})
</script>
Related
My app shows an HTML page with multiple views, and each view can be conditionally built from multiple HTML templates.
I want to edit each HTML file and add a few lines at the top, something like
<div ng-if="showFileNames”>
<hr>
<p>Start of file {{how do I get the file name}}</p>
<hr>
</div>
And maybe the same at the footer.
Thus, by setting $scope. showFileNames to true, I could switch the display of file names on/off and see how my page is actually composed (is this clear, or should I add some ascii art?).
I could just hard code {{how do I get the file name}} in each file, but doing it dynamically means that I can more easily add the code to each file, plus it guards against files being renamed.
Can it be done? If so, how?
[Update] I just realized that the question didn't explain well enough. Sorry.
I need to stress that part where I said
each view can be conditionally built from multiple HTML templates
While the view is state based, its contents are built from different <ng-include> files, based on data.
So, state A might include A.html, but, based on the data, that view might <ng-include> B.html, C.html and E.html, or it might <ng-include> F.html, G.html and H.htFl - and I want to show the file name of each at the head & foot of the part of the view shown by each file
Update: You may have templates loaded with ui-view and ng-include. The example given bottom of this answer has a nice generic directive to return the corresponding template name even though if you nested ui-view and ng-include together. Click through "Home", "About" and "Named View" link inside "About".
Few theory goes below,
If you use ui-view then you can try this with $state.current.templateUrl as below.
<div ng-if="showFileNames”>
<hr>
<p>Start of file {{$state.current.templateUrl}}</p>
<hr>
</div>
The above will work if you had defined your state as below,
.state('state1', {
url: '/state1',
templateUrl: 'partials/state1.html'
controller: 'State1Ctrl'
})
But if you had defined this as named views as below,
$stateProvider
.state('report',{
views: {
'filters': {
templateUrl: 'report-filters.html',
controller: function($scope){ ... controller stuff just for filters view ... }
}
}
}
})
Then, better you can have a method assigned with the $rootScope as below and pass the $state.current.views from the html to the function.
$rootScope.getTemplate = function(view) {
var keys = Object.keys(view);
if(keys.length === 0) return '';
return view[keys[0]].templateUrl;
};
and the html,
<div ng-if="showFileNames”>
<hr>
<p>Start of file {{getTemplate($state.current.views)}}</p>
<hr>
</div>
But you can have a look at the below generic directive which covers ui-view, nested ui-view, named ui-view and ng-include and even a bit of complex nesting with ui-view and ng-include.
Generic directive with an example page
Click through "Home", "About" and "Named View" link inside "About"
var app = angular.module('app', ['ui.router']);
app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home.html',
controller: 'TestController'
})
.state('about', {
url: '/about',
templateUrl: 'about.html',
controller: 'TestController'
})
.state('about.named', {
url: '/named',
views: {
'named': {
templateUrl: 'named.html',
controller: 'TestController'
}
}
});
}
]);
app.controller('TestController', function($scope) {
});
app.directive('templateName', ['$state', function($state) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var templateName = $state.current.templateUrl;
var includesParent = $(element).closest('[ng-include]');
if(includesParent && includesParent.length > 0) {
if(includesParent.find('[ui-view]').length === 0) {
templateName = scope.$eval(includesParent.attr('ng-include'));
}
}
if(!templateName && $state.current.views) {
var uiViewParent = $(element).closest('[ui-view]');
var viewName = $state.current.views[uiViewParent.attr('ui-view')];
if(viewName) {
templateName = viewName.templateUrl;
}
}
element.html(templateName);
}
};
}]);
angular.bootstrap(document, ['app']);
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.min.js"></script>
<div>
<!-- NAVIGATION -->
<nav class="navbar navbar-inverse" role="navigation" ng-include="'nav.html'">
</nav>
<!-- MAIN CONTENT -->
<div class="container">
<!-- THIS IS WHERE WE WILL INJECT OUR CONTENT ============================== -->
<div ui-view></div>
</div>
<script type="text/ng-template" id="home.html">
<h3>Home Page</h3>
<p>Start of file: <span template-name></span></p>
</script>
<script type="text/ng-template" id="about.html">
<h3>About Page<h3>
<p>Start of file: <span template-name></span></p>
<div ng-include="'aboutUs.html'"></div>
</script>
<script type="text/ng-template" id="aboutUs.html">
<h3>About us<h3>
<p>Start of file: <span template-name></span></p>
<a ui-sref="about.named">Named View</a>
<div ui-view="named"></div>
</script>
<script type="text/ng-template" id="named.html">
<h3>Named View<h3>
<p>Start of file: <span template-name></span></p>
</script>
<script type="text/ng-template" id="nav.html">
<div class="navbar-header">
<a class="navbar-brand" ui-sref="#">Start of file: <span template-name></span></a>
</div>
<ul class="nav navbar-nav">
<li><a ui-sref="home">Home</a></li>
<li><a ui-sref="about">About</a></li>
</ul>
</script>
</div>
all.
This is a test to see if I can connect to the Open Weather Map api and successfully display an item of data from it (for now I am just trying to get the city name for a given latitude and longitude).
I am doing this inside a CodePen pen, by the way.
The problem is that nothing appears on the page - I get no city name at all.
What is this missing? (I have obscured my api key)
<html><body>
<div class="Text-center">
<h1> Local Weather</h1>
<h3>Front End Dev Project</h3>
<ul class ="list-unstyled">
<li class="btn btn-default" id="city"></li>
</ul>
<div>
</body></html>
<script>
$(document).ready(function(){
var long= -77.0506895;
var lat = 38.8925157;
var api = 'http://api.openweathermap.org/data/2.5/weatherlat='+lat+'&lon'+long+'=&appid=(HIDDEN)';
$.getJSON(api, function(data){
var city = data.name;
$("#city").html(city);
});
});
</script>
This is the correct url, please correct your url
http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid={AppKey}
and the response below
{
"coord":{
"lon":138.93,
"lat":34.97
},
"weather":[
{
"id":800,
"main":"Clear",
"description":"clear sky",
"icon":"01n"
}
],
"base":"cmc stations",
"main":{
"temp":297.374,
"pressure":1018.36,
"humidity":93,
"temp_min":297.374,
"temp_max":297.374,
"sea_level":1027.9,
"grnd_level":1018.36
},
"wind":{
"speed":7.46,
"deg":243.504
},
"clouds":{
"all":0
},
"dt":1467816873,
"sys":{
"message":0.0045,
"country":"JP",
"sunrise":1467747404,
"sunset":1467799281
},
"id":1851632,
"name":"Shuzenji",
"cod":200
}
OK, the following works OUTSIDE of CodePen. If I use it inside CodePen, it is blocking the JSON call somehow. If I run this however in Chrome from a version written in NotePad, it returns "Shuzenji" just fine.
But that is an issue for another thread.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
var api = 'http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=52481ca8a499564783f5f082863acac1';
$.getJSON(api, function(data){
var city = data.name;
$("#city").html(city);
});
});
</script>
</head>
<body>
<div class="Text-center">
<h1> Local Weather</h1>
<h3>Front End Dev Project</h3>
<ul class ="list-unstyled">
<li class="btn btn-default" id="city"></li>
</ul>
<div>
</body>
</html>
Hi I'm trying to make a slider I got off the internet to work, but, I keep getting errors. In gallery.html, when I put the slider element at the top I get nothing, when I put it at the bottom I get errors. The error is something along the lines
Error: [$compile:tplrt] http://errors.angularjs.org/1.4.8/$compile/tplrt?p0=slider&p1=partials%2Fgallery.html
Changed my code to match the suggestions in one of the comments.
I'm no longer getting the error to do with not have just 1 root element. Now, I can't get the next and previous to work. It just redirects me to the main page.
Note:
- gallery.html and slider.html are in a folder called partials
- all the images are in a folder called img
Thanks in advance!
index.html
<!DOCTYPE html>
<html lang="en" ng-app="myapp">
<head>
<!-- ANGULAR IMPORTS -->
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/ui-router-master/release/angular-ui-router.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://code.angularjs.org/1.4.7/angular-animate.js"></script>
<!-- JS FILES -->
<script src="js/controller.js"></script>
<script src="js/directives.js"></script>
<link href='css/app.css' rel='stylesheet' type='text/css'>
</head>
<body class="container">
<div class="navbar">
<a class="brand" href="#">Quick Start</a>
<ul class="nav">
<li><a ui-sref="state1">State 1</a></li>
<li><a ui-sref="state2">State 2</a></li>
<li><a ui-sref="gallery">Gallery</a></li>
</ul>
</div>
<div class="dynamiccontent">
<div ui-view></div>
</div>
<!-- App Script -->
<script>
/** MAIN ANGULAR VAR */
var myapp = angular.module('myapp', [
/**IMPORT DEPENDENCIES*/
'ui.router',
'ngAnimate',
/**FILE DEPENDENCIES*/
'appController',
'slider.directive'
]);
/** UI-ROUTING */
myapp.config(function($stateProvider, $urlRouterProvider){
// For any unmatched url, send to /state1
$urlRouterProvider.otherwise("/state1")
$stateProvider
.state('state1', {
url: "/state1",
templateUrl: "partials/state1.html"
})
.state('state1.list', {
url: "/list",
templateUrl: "partials/state1.list.html",
controller: 'state1controller'
})
.state('gallery', {
url: "/gallery",
templateUrl: "partials/gallery.html",
controller: 'slidercontroller'
})
.state('state2', {
url: "/state2",
templateUrl: "partials/state2.html"
})
.state('state2.list', {
url: "/list",
templateUrl: "partials/state2.list.html",
controller: 'state2controller'
});
});
</script>
</body>
</html>
controller.js
var appController = angular.module('appController',[]);
appController.controller('state1controller', ['$scope', function($scope){
$scope.items = ["A", "List", "Of", "Items"];
}]);
appController.controller('state2controller', ['$scope', function($scope){
$scope.things = ["A", "List", "Of", "Items"];
}]);
appController.controller('slidercontroller', ['$scope', function($scope) {
$scope.pictures=[{src:'img1.png',title:'Pic 1'},{src:'img2.jpg',title:'Pic 2'},{src:'img3.jpg',title:'Pic 3'},{src:'img4.png',title:'Pic 4'},{src:'img5.png',title:'Pic 5'}];
}]);
directive.js
angular.module('slider.directive', [])
.directive('slider', function ($timeout) {
return {
restrict: 'AE',
replace: true,
scope:{
pictures: '='
},
link: function (scope, elem, attrs) {
scope.currentIndex=0;
scope.next=function(){
scope.currentIndex<scope.pictures.length-1?scope.currentIndex++:scope.currentIndex=0;
};
scope.prev=function(){
scope.currentIndex>0?scope.currentIndex--:scope.currentIndex=scope.pictures.length-1;
};
scope.$watch('currentIndex',function(){
scope.pictures.forEach(function(image){
image.visible=false;
});
scope.pictures[scope.currentIndex].visible=true;
});
/* Start: For Automatic slideshow*/
var timer;
var sliderFunc=function(){
timer=$timeout(function(){
scope.next();
timer=$timeout(sliderFunc,5000);
},5000);
};
sliderFunc();
scope.$on('$destroy',function(){
$timeout.cancel(timer);
});
/* End : For Automatic slideshow*/
},
templateUrl:'partials/slider.html'
}
});
gallery.html
<slider pictures="pictures"></slider>
slider.html
<div class="slider">
<div class="slide" ng-repeat="image in pictures">
<img ng-src="img/{{image.src}}"/>
</div>
<div class="arrows">
<img src="img/left-arrow.png"/>
<img src="img/right-arrow.png"/>
</div>
</div>
You are mixing several concerns here. partials/gallery.html is used as a template for your directive and your page. This leads to the directive being used itself in it's own template.
The solution is to remove your directive code from gallery.html and use it in a new file slider.html.
directive.js
.directive('slider', function ($timeout) {
return {
...
templateUrl:'partials/slider.html'
slider.html
<div class="slider">
<div class="slide" ng-repeat="image in images">
<img ng-src="img/{{image.src}}"/>
</div>
<div class="arrows">
<img src="img/left-arrow.png"/>
<img src="img/right-arrow.png"/>
</div>
</div>
gallery.html
<slider images="pictures"/>
First off - the error does have to do with the root element.
https://docs.angularjs.org/error/$compile/tplrt
Template for directive '{0}' must have exactly one root element. {1}
Now that you fixed that issue - your infinite loop is called because you're trying to populate the slider directive with gallery.html - but in that template, you're calling the slider directive. So that's an infinite loop.
I am trying to render a listview on a second page using jquery.mobile.
I am using a single HTML with multiple "pages".
<div data-role="page" id="foo">
List
</div>
<div data-role="page" id="bar">
<div id="ListDiv">
<ul id="listview" data-role="listview" data-inset="true">
</ul>
</div>
</div>
<!--application UI goes here-->
<script type="text/javascript">
$("#loadList").click(function(){
$.getJSON(
"http://localhost/index.php/api/list",{format: "json"},
function(data){
var output = '';
$.each(data, function(key, val) {
output += '<li>' + val +'</li>';
});
$('#listview').append(output).listview('refresh');
});
});
But the problem now is when I click the #loadList button, it does take me to the #bar page, however, it doesn't seem $("#loadList").click() gets executed, because the list doesn't show up on the #bar page. Namely, nothing gets appended to #listView.
Any thoughts?
First there's a problem in this code, $.getJSON loading logic is false. Change page can not be used in a same time with $.getJSON.
There are 2 ways you can make this work:
Remove onclick event and load your data during second page initialization:
$(document).on('pagebeforeshow', '#bar', function(){
$.getJSON(
"http://localhost/index.php/api/list",{format: "json"},
function(data){
var output = '';
$.each(data, function(key, val) {
output += '<li>' + val +'</li>';
});
$('#listview').append(output).listview('refresh');
});
});
});
Unfortunately there's a problem with this solution. Used page event is not going to wait for $.getJSON, so in some cases your listview will be empty when page loads and content will suddenly appear. So this solution is not that great.
Second solution is remove href="#bar" attribute from the button but leave a click event. When $.getJSON action is successful the use changePage function and load next page. In case there's a problem with accessing second page listview store your result (In this ARTICLE you will find how, or HERE) and append it again during a pagebeforeshow event of a #bar page.
I made you a working jsFiddle example: http://jsfiddle.net/Gajotres/GnB3t/
HTML :
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h3>
First Page
</h3>
</div>
<div data-role="content">
Load JSON data
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3>
Second Page
</h3>
Back
</div>
<div data-role="content">
<h2>Simple list</h2>
<ul data-role="listview" data-inset="true" id="movie-data" data-theme="a">
</ul>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
</body>
</html>
JS :
$(document).on('pagebeforeshow', '#index', function(){
$('#populate-button').on('click',function(e,data){
$.ajax({url: "http://api.themoviedb.org/2.1/Movie.search/en/json/23afca60ebf72f8d88cdcae2c4f31866/The Goonies",
dataType: "jsonp",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
success: function (result) {
ajax.jsonResult = result;
$.mobile.changePage("#second");
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
});
});
$(document).on('pagebeforeshow', '#second', function(){
ajax.parseJSONP(ajax.jsonResult);
});
var ajax = {
jsonResult : null,
parseJSONP:function(result){
$('#movie-data').empty();
$('#movie-data').append('<li>Movie name:<span> ' + result[0].original_name+ '</span></li>');
$('#movie-data').append('<li>Popularity:<span> ' + result[0].popularity + '</span></li>');
$('#movie-data').append('<li>Rating:<span> ' + result[0].rating+ '</span></li>');
$('#movie-data').append('<li>Overview:<span> ' + result[0].overview+ '</span></li>');
$('#movie-data').append('<li>Released:<span> ' + result[0].released+ '</span></li>');
$('#movie-data').listview('refresh');
}
}
You have id="loadList)", that is, with a closing parenthesis in
List
Maybe this is causing your problem?
I'm having difficulty using my code:
<input id="button" type="button" value="Load"/>
<div id="content"> </div>
<script src="js/ajax.js" type="text/javascript"></script>
Using ajax: It seems to not run.
$('#button').click(function() {
$.ajax({
url: 'page.html',
success: function(data) {
$('#content').html(data);
}
});
});
page html contains <span>Hello</span>
Can anyone help me I don't know whats wrong I've tested with this and works properly:
<input type="text" onclick="$(this).hide();"/>
NOTE i have <script src="js/jquery.js" type="text/javascript"></script>
Did you link the jquery.js library ?
first load jquery library at the top of your page
Try specifying a dataType:
use the code below
<script>
$(function($) {
$('#button').click(function() {
$.get('page.html',function(data)
{
$("#content").html(data);
},"html")
});
});
</script>
have fun:)