I am using angularjs to automatically change time in a simple html file by using an ng-controller but its only showing the initial time but not updating later
here is the index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Testing</title>
</head>
<body ng-app="myapp">
<div ng-controller="myctrl">
<h1>{{data()}}</h1>
</div>
<script TYPE="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
and the main.js
var app=angular.module('myapp',[]);
app.controller("myctrl",function($scope)
{
$scope.data=function()
{
var d = new Date();
var n = d.getTime();
return n;
}
})
How do I make it update every time...?
data() only gets rand when the template is compiled. You need to use a timer to update the value.
Something like this would work.
html template
<div ng-controller="timer" ng-app>
{{time | date:'h:m:ss'}}
</div>
controller
function timer($scope, $interval){
$scope.time = Date.now();
$interval(function(){
$scope.time = Date.now();
},1000);
}
Also you can use Date.now() instead of (new Date()).getTime()
You never update $scope.data,Angular wont do that for you.
var timeout;
var changeTime=function(){
$scope.data = (new Date()).getTime();
timeout = $timeout(changeTime,1000);
}
timeout= $timeout(changeTime,1000);
You're only calling data once in this example. For it to update in real-time, you'll need the date called continuously like so:
var app=angular.module('myapp',[]);
app.controller("myctrl",function($scope, $timeout)
{
// called every second
var getTime = function(){
$scope.data = (new Date()).getTime();
$timeout(getTime, 1000, true);
}
getTime();
})
And in your view just get rid of the data() invocation and instead reference the model:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Testing</title>
</head>
<body ng-app="myapp">
<div ng-controller="myctrl">
<h1>{{data}}</h1>
</div>
<script TYPE="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Related
I'm making a site that, depending on the user's time of the day, will show a night, afternoon or morning image.
But as it seems, the JS isn't working due to a Syntax Error on calling the function with "onload=" in the tag <body>. My VS Code Javascript higlighter isn't working on the words window, document nor getElementById.
Which part of my JS could be wrong?
Here's the HTML
<!DOCTYPE html>
<html lang="pt-br">
<head>
<script type="javascript" src="/script.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie-edge">
<link rel="stylesheet" href="/style.css">
</head>
<body onload="load()">
<section>
<div id="msg">
Message here
</div>
<div id="foto">
<img id="image" src="img/afternoon.png">
</div>
</section>
<footer>
<p>© Koala</p>
</footer>
</body>
</html>
And here's the JS
function load(){
var msg = window.document.getElementById('msg');
var img = window.document.getElementById('image');
var dt = new.Date();
var hour = dt.getHours();
msg.innerHTML = 'Now it is ${hour} hours.';
if (hour>= 0 && hour < 12) {
img.src = 'img/morning.png';
} else if (hour => 12 && hour < 18) {
img.src = 'img/afternoon.png';
} else {
img.src = 'img/night.png';
}
}
PS: I've tried running it on Mozilla and Chrome. No success.
The error appears to be with this line:
var dt = new.Date();
To instantiate a new Date object, you need to use this syntax:
var dt = new Date();
Once this syntax error is fixed, then the JS file should be loaded properly and then the onload attribute will be able to fire the load function.
Here's a working demo: https://codesandbox.io/s/stack-overflow-onload-8opgp?file=/script.js
I have a function that returns some HTML fragment that I store in a variable called data, with its whole structure. What I want is to extract from it some of those parts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script id="hello">
</script>
</head>
<body>
</body>
</html>
For example, I want to get the body and save it in a new variable:
var body = data.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
Where data is the HTML text as a string that the original function is returning.
Is there any way I could save an specific script, from its ID (in this case with id = hello), and save it in another variable??
Thank you very much
var newVar = $("#hello").html();
Let's suppose you have an HTML string in a variable, for example
var foo = '<body><span>bar</span></body>';
Now, let's initialize a parser, to convert this into HTML:
var parser = new DOMParser();
var doc = parser.parseFromString(foo, "text/html");
Now, you can read anything from foo, as it is converted into HTML:
document.getElementsByTagName("body")[0].innerHTML = doc.querySelectorAll("body")[0].innerHTML;
$html = document.querySelector("body").innerHTML;
$hello = document.getElementById("hello").innerHTML;
console.log($html);
console.log($hello);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script id="hello">
// script data
</script>
</head>
<body>
</body>
</html>
I have a string like var message = "you are moving to {{output.number}}";
I want this to be put to div element. i tried using $("#message").html(message);
but it just printed the whole string for me. I want to have the output.number print the value it had. Is it possible to achieve what i want?
I am using angular.js 1.5.
Use $interpolate service like:
var message = $interpolate("you are moving to {{number}}")(output)
// or
var message = $interpolate("you are moving to {{output.number}}")($scope)
I hope you are looking for something like this. You can do it by using the scope variable inside the controller.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.bootcss.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="number" ng-model="output.number" />
<button ng-click="AppendItem()">Append</button>
<div id="message"></div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.output = {};
$scope.AppendItem = function () {
var string = "Your Number is " + $scope.output.number;
$("#message").html(string);
}
});
</script>
</body>
</html>
You are almost there just try :
$scope.output.number = '123';
var message = "you are moving to" + output.number;
$("#message").html(message);
Don't put variable inside "" quotes.
When we are going to append a string variable to another string variable then we need to use append operator ie., "+". Here is an example.
var output.number = 10;
var message = "you are moving to " + output.number;
$("#message").html(message);
You can do like this using $compile:
$compile(angular.element(document.querySelectorAll('#message')[0]).html("you are moving to {{output.number}}"))($scope);
Add $compile as dependency in your controller.
All the best.
You can try this:
<html ng-app="app">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body ng-controller="appCtrl">
<p id="message"></p>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"> </script>
</body>
JS:
Should not write DOM Manipulation code inside controller, but can get the idea how to do it.
var app = angular.module('app', []);
app.controller('appCtrl', function($scope, $interpolate){
var msg = "you are moving to {{number}}";
$scope.number = 10;
$('#message').html($interpolate(msg)($scope));
});
I have the below code in a html page, running it though I keep getting an error stating that "angular is not defined" I have included angular in the head so i'm not sure why it can't locate it, the url to angular i'm also able to hit directly.
<!DOCTYPE>
<html ng-app="test">
<head>
<title>
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
</title>
</head>
<body ng-controller="TestController">
<form name="CopyFile" ng-submit="copy(fileId)">
<input type="text" ng-model="fileId"/>
<input type="submit" value="Copy"/>
</form>
<div>{{ message }}</div>
<div>{{ error }}</div>
<script type="text/javascript">
(function () {
var app = angular.module("test", []);
var testController = function ($scope, $http) {
$scope.copy = function (fileId) {
$http.get("http://localhost/test/copy/prod.aspx/ToProd?fileId=" + fileId)
.then(onComplete, onError);
};
var onComplete = function (response) {
$scope.message = response;
};
var onError = function (reason) {
$scope.error = "File could not be copied " + reason;
};
};
app.controller("TestController", ["$scope", "$http"], testController);
} ());
</script>
</body>
</html>
This may not be the cause but you don't want your angular include inside of your title. It should be something more like this:
<!DOCTYPE>
<html ng-app="test">
<head>
<title>My Page</title>
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
</head>
.....
You gave <script> inside <title>?
<title>
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
</title>
Please remove it outside.
Sorry, I am new to javascript. I am trying to call an object from inside a function to allow me to get a variable from a flash file at set intervals. For some reason the object is not working inside the timer function.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DIY Map</title>
<style>
* { margin:0; padding:0; }
</style>
</head>
<body style="font-family:verdana;color:#999; background-image:url('bg.png'); background-repeat:no-repeat;">
<script type="text/javascript" src="js/JavaScriptFlashGateway.js"></script>
<script type="text/javascript" src="js/Exception.js"></script>
<script type="text/javascript" src="js/FlashTag.js"></script>
<script type="text/javascript" src="js/FlashSerializer.js"></script>
<script type="text/javascript" src="js/FlashProxy.js"></script>
<script type="text/javascript">
var uid = new Date().getTime();
var flashProxy = new FlashProxy(uid, 'js/JavaScriptFlashGateway.swf');
var tag = new FlashTag('world.swf?data_file=data.xml, 600, 325);
tag.setFlashvars('lcId='+uid);
tag.write(document);
</script>
//flashProxy.call works here:
<p>Zoom Out
Get new data
<p>getZoom | getCoords</p>
<script type="text/javascript">
// Start the refreshing process
var seconds = 3;
var zoom;
var coords;
//timer loop
function checkmap()
{
//flashProxy doesn't work here
flashProxy.call('getCoords');
flashProxy.call('getZoom');
alert (coords);
alert (zoom);
setTimeout('checkmap()',seconds * 1000);
}
checkmap();
//Returns results here:
function gotCoords(n)
{
coords = n;
}
function gotZoom(n)
{
zoom = n;
}
</script>
To clarify, I am trying to get the flashProxy.call('****') to work in the checkmap() function. Thanks in advance.
I found the problem... it was that because there was no timer to start the inital flashproxy.call it was executing before the flash was loaded. I just replaced
checkmap();
with another
setTimeout('checkmap()',seconds * 1000);
Thanks everyone anyway
Did you know you have an extra/unclosed script tag in your source? This would cause problems.
<script type="text/javascript"> // This is your opening tag
<script type="text/javascript"> // Oops, this is parsed by the script engine
var uid = new Date().getTime();
var flashProxy = new FlashProxy(uid, 'js/JavaScriptFlashGateway.swf');
var tag = new FlashTag('world.swf?data_file=data.xml, 600, 325);
tag.setFlashvars('lcId='+uid);
tag.write(document);
</script>
The above code would throw a syntax error in any javascript engine and halt further execution.
Your source is also missing a ' on the following line:
var tag = new FlashTag('world.swf?data_file=data.xml, 600, 325);