Why the time cann't be update when using setInterval? - javascript

I am learning AngulaJS, here is the code:
<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ClockCtrl">
Current time is: {{ time.now }}
</div>
</body>
</html>
the script.js:
function ClockCtrl($scope){
var time = {};
time.now = new Date().toString();
$scope.time = time;
setInterval(function(){
$scope.time.now = new Date().toString();
console.log(time.now);
}, 1);
}
But i don't know why the time cann't be update in the html display?

You should use $interval directive instead of setInterval, which will internally call $scope.$apply() to update the bindings
function ClockCtrl($scope, $interval){
$interval(function(){
$scope.time.now = new Date().toString();
}, 1000);
////Or, You can use $scope.$apply()
//setInterval(function () {
// $scope.time.now = new Date().toString();
// $scope.$apply();
//}, 1000);
}
DEMO

Related

Angular JS code not working

I copied this angularjs code from a book "ng-book". But it is not working at all..........................................................
<!DOCTYPE html>
<html ng-app="">
<head>
<title>Simple App</title>
</head>
<body>
<div ng-controller="MyController">
Hello <span ng-bind="clock"></span>
</div>
<script src="angular-1.5.7/angular.js">
</script>
<script type="text/javascript">
function MyController($scope){
$scope.clock = new Date();
var updateClock = function () {
$scope.clock = new Date();
};
setInterval(function() {
$scope.$apply(updateClock);
}, 1000);
updateClock();
};
</script>
</body>
</html>
Use $interval rather and setInterval.
No need of $scope.$apply() when you use angular's $interval
You need the ng-app defined
The controller definition should be like in the snippet
Here is a working code snippet
var demoApp = angular.module('demoApp', []);
demoApp.controller('MyController', function($interval, $scope) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
$interval(function() {
updateClock();
}, 1000);
updateClock();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Simple App</title>
</head>
<body ng-app="demoApp">
<div ng-controller="MyController">
Hello <span ng-bind="clock"></span>
</div>
</body>
What you are doing is not the most efficient way. For example you could use $interval and so on..
But since you are just starting with Angular, I've made the code working with minimal addition or modification so you can understand:
//addition-start
var app = angular.module('myApp', []);
app.controller("MyController", MyController);
//addition-end
function MyController($scope) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(function() {
$scope.$apply(updateClock);
}, 1000);
updateClock();
};
<!DOCTYPE html>
<!--can be modified to ng-app="myApp"but will work otherwise too -->
<html ng-app="">
<head>
<title>Simple App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js "></script>
</head>
<body>
<div ng-controller="MyController">
Hello <span ng-bind="clock "></span>
</div>
</body>
</html>
first read how to difine angular module and how it works.you didn't define module in html
<!DOCTYPE html>
<html ng-app="testapp">
<head>
<title>Simple App</title>
<script src="angular-1.5.7/angular.js"> </script>
</head>
<body>
<script type="text/javascript">
var app=angular.module('testapp',[]);
app.controller('MyController',function($scope,$setInterval){
$scope.clock = new Date();
var updateClock = function () {
$scope.clock = new Date();
};
$setInterval(function() {
$scope.$apply(updateClock);
}, 1000);
updateClock();
});
</script>
<div ng-controller="MyController">
Hello <span ng-bind="clock"></span>
</div>
</body>
</html>
You forgot to define your module ng-app
<!DOCTYPE html>
<html ng-app="demoApp">
<head>
<title>Simple App</title>
</head>
<body>
<div ng-controller="MyController">
Hello {{clock}}</span>
</div>
<script src="angular-1.5.7/angular.js"></script>
<script type="text/javascript">
var app = angular.module('demoApp',[]);
function MyController($scope){
$scope.clock = new Date();
var updateClock = function () {
$scope.clock = new Date();
};
$interval(function() {
updateClock();
}, 1000);
updateClock();
};
</script>
</body>
</html>
Doc
Difference between set-interval and $interval
ng-bind has one-way data binding ($scope --> view). It has a shortcut {{ val }} which displays the scope value $scope.val inserted into html where val is a variable name.

Javascript / JQuery Set Cookie on page load

I would appreciate some orientation in the following issue.
I want to set a cookie when a page loads. The cookie value should taken from a div data-myifo attribute within the HTML code.
My current code looks as follows:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id=someid data-myinfo="yyyyy">Hello World</div>
<script type="text/javascript">
function set_cookie (cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString()
+ "; path=/";
}
function get_atribute () {
var myinfo = document.getElementsByTagName("div")[0].getAttribute("data-myinfo");
set_cookie ("My_Cookie", myinfo);
}
$(document).ready(function () {
get_atribute ();
});
</script>
</body>
</html>
I've tried running the function get_atribute () using a onclick="get_atribute ()" and that way it works but not on page load or after.
What am I missing?
No need to use jQuery here
Could just use:
(function() {
get_attribute();
})();

Angular-timer siddii

in my web app (which is with angularJs in the front part and with Symfony2 in the back part) i need to integrate a timer (count down of a quizzer) i found this timer https://github.com/siddii/angular-timer on github and it seems to be cool but i don't the integration in my webapp works but when i try to start the counter on an event (button click) it don't works, in fact i tried this script:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Example - Single Timer Example</title>
<script src="../angular/angular.min.js"></script>
<script src="../app/js/timer.js"></script>
<script>
angular.module('MyApp', ['timer']);
function MyAppController($scope) {
$scope.timerRunning = true;
$scope.startTimer = function (){
$scope.$broadcast('timer-start');
$scope.timerRunning = true;
};
$scope.stopTimer = function (){
$scope.$broadcast('timer-stop');
$scope.timerRunning = false;
};
$scope.$on('timer-stopped', function (event, data){
console.log('Timer Stopped - data = ', data);
});
}
MyAppController.$inject = ['$scope'];
</script>
</head>
<body ng-app="MyApp">
<div ng-controller="MyAppController">
<h1>AngularJS - Single Timer Example</h1>
<h3><timer/></h3>
<button ng-click="startTimer()" ng-disabled="timerRunning">Start Timer</button>
<button ng-click="stopTimer()" ng-disabled="!timerRunning">Stop Timer</button>
</div>
<br/>
</body>
</html>
and i got this error:
Argument 'MyAppController' is not a function, got undefined
any one can help me plz ?
after some changes the my code becomes :
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Example - Single Timer Example</title>
<script src="../angular/angular.min.js"></script>
<script src="../app/js/timer.js"></script>
<script>
var myApp = angular.module('myApp', ['timer']);
myApp.controller('MyAppController', ['$scope', function ($scope)
{
$scope.timerRunning = true;
$scope.startTimer = function (){
$scope.$broadcast('timer-start');
$scope.timerRunning = true;
};
$scope.stopTimer = function (){
$scope.$broadcast('timer-stop');
$scope.timerRunning = false;
};
$scope.$on('timer-stopped', function (event, data){
console.log('Timer Stopped - data = ', data);
});
}]).$inject = ['$scope'];
</script>
</head>
<body ng-app="myApp">
<div ng-controller="MyAppController">
<h1>AngularJS - Single Timer Example</h1>
<h3><timer/></h3>
<button ng-click="startTimer()" ng-disabled="timerRunning">Start Timer</button>
<button ng-click="stopTimer()" ng-disabled="!timerRunning">Stop Timer</button>
</div>
<br/>
</body>
</html>
and i'm getting this beauty :/
Unknown provider: I18nServiceProvider <- I18nService

Auto Refresh Input Time object without reloading page

I have an input field that I would like to refresh every 2 seconds or so. However,I can't seem to get the 'setInterval' right because it is not updating my ID. Should I not be using the
ID to declare the refresh? Any help will be most appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" content="HTML,CSS,XML,JavaScript">
<script src="Scripts/Global.js" type="text/javascript"></script>
<script src="Scripts/jquery.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="Styles/Design.css">
</head>
<body>
Time: <input type="time" id="theTime">
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
var myVar = setInterval(function(){ myTimer() }, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("theTime").innerHTML = t;
}
</script>
<script type="text/javascript">
$(document).ready( function() {
var now = new Date();
//now2 prevents the milliseconds from showing up in the input
var now2 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours()-8, now.getMinutes(), now.getSeconds());
$('#theTime')[0].valueAsDate = now2;
});
</script>
</body>
</html>
You're setting the innerHTML of myTimer, where you should really be setting the valueAsDate, like in your $(document).ready function.
Here's how myTimer should look:
function myTimer() {
var now = new Date();
var now2 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours()-8, now.getMinutes(), now.getSeconds());
$('#theTime')[0].valueAsDate = now2;
}
and then you can call myTimer() from within your $(document).ready:
$(document).ready( function() {
myTimer();
});
you are trying to set the innerHTML of an input field. use $('#theTime').val() instead!

Javascript function checking dates

Hi I am new to Javascript and am trying to create a function that checks two dates. I have read it is useful to put the JS in the head part of the document, but this is not returning anything. I am also new to stackoverflow so I hope I did this correctly. :) Does anyone see the error?
<!DOCTYPE html>
<html>
<head>
var myDate = new Date(); // Your timezone!
var myEpoch = myDate.getTime()/1000;
var deadline = '1341596750.000';
document.write(myEpoch);
document.write("<br>",deadline);
if (myEpoch < deadline) {
document.write("<p>Just in time!</p>");
} else {
document.write("<p>Too late!</p>");
}
</head>
<body>
<br><br><br><br>http://www.epochconverter.com/
</body>
</html>
You have to mention it's a script using <script>. Also you shouldn't output DOM in the <head> like you are doing with document.write. Manipulate the DOM like this instead:
<head>
<script type="text/javascript">
var myDate = new Date(); // Your timezone!
var myEpoch = myDate.getTime()/1000;
var deadline = '1341596750.000';
document.write(myEpoch);
document.write("<br>",deadline);
if (myEpoch < deadline) {
document.getElementById("useme").innerHTML("Just in time!");
} else {
document.getElementById("useme").innerHTML("Too late!");
}
</script>
</head>
<body>
<p id="useme"></p>

Categories

Resources