I am trying to implement a simple timer in angularJS. But timeout function is not working though it is suggested by everyone.
<!doctype html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-sanitize.min.js"></script>
</head>
<body>
<div ng-app="ss" ng-controller="mainCtrl">
{{timeInMs}}
</div>
<script>
var myApp = angular.module("ss", ['ngSanitize']);
myApp.controller('mainCtrl', function ($sce, $scope) {
$scope.timeInMs = 10;
var countUp = function() {
$scope.timeInMs+= 500;
$timeout(countUp, 500);
}
$timeout(countUp, 500);
});
</script>
</body>
</html>
When I comment out the " $timeout(countUp, 500);" line, the code works without error but timer doesn't work. Do i need to include any more javascript file?
Thanks in advance.
You have to inject the $timeout service to the controller
var myApp = angular.module("ss", []);
myApp.controller('mainCtrl', function ($sce, $scope, $timeout) {
$scope.timeInMs = 10;
var countUp = function () {
$scope.timeInMs += 500;
$timeout(countUp, 500);
}
$timeout(countUp, 500);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ss" ng-controller="mainCtrl">
{{timeInMs}}
</div>
Related
I have 2 files. First one :
<script>
var demo=angular.module('demo', []);
demo.controller('scoresCtrl', function($scope, $http) {
$http.get('http://localhost/scores').then(function(response) {
$scope.scores = response.data;
});
});
</script>
Another file index.html
<head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="scoresCtrl.js"></script>
<script>
function run(){
var data=angular.element(document.getElementById("scoresBodyId")).scope().scores;
alert(data);
}
</script></head>
<body onload="run()" id="scoresBodyId" ng-controller="scoresCtrl" >
</body>
When I tried to display alert(data) , I got undefined
but when I replace onload by onclick , after Clicking I obtained my value. I would like to use onload. Thanks for your explanation and your help.
You need to change onload to ng-init to call your function on body
Controller
var demo = angular.module('demo', []);
demo.controller('scoresCtrl', function($scope, $http) {
$scope.run = function() {
$http.get('http://localhost/scores').then(function(response) {
$scope.scores = response.data;
alert($scope.scores);
});
}
});
index.html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="scoresCtrl.js"></script>
</head>
<body ng-init="run()" id="scoresBodyId" ng-controller="scoresCtrl">
</body>
I am having a problem sending a value of JavaScript variable to Angular js variable. I want to send a value in dataArray variable in JavaScript to Angular js variable $scope.test
html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="angular.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
// $("#fileUpload").load('test.csv');
$.get("test.csv", function(data) {
alert(data);
var rows = data.split("\r\n");
if(rows.length>0){
alert("inside if");
var firstRowCells = GetCSVCells(rows[0], ",");
var dataArray = new Array();
for(var i=1;i<rows.length;i++)
{
var cells = GetCSVCells(rows[i], ",");
var obj = {};
for(var j=0;j<cells.length;j++)
{
obj[firstRowCells[j]] = cells[j];
}
dataArray.push(obj);
}
$("#dvCSV").html('');
alert(dataArray);
$("#dvCSV").append(JSON.stringify(dataArray));
var myjson=JSON.stringify(dataArray);
//alert(myjson);
}
});
function GetCSVCells(row, separator){
return row.split(separator);
}
});
</script>
</head>
<body>
<div id="container">
Test
</div>
<div ng-app="sortApp" ng-controller="mainController">
<div id="dvCSV" ng-model="dataf" ng-bind="bdc">dfsgdfd</div>
</div>
<script src="app.js"></script>
</body>
</html>
app.js:
angular.module('sortApp', [])
.controller('mainController', function($scope) {
window.alert("Angular");
window.alert("asdfad"+$scope.bdc);
$scope.test=$scope.dataf;
window.alert($scope.myjson);
window.alert("test"+$scope.test.value);
You can do this all jquery stuff in angular using http service of angular js.
For simple http service you can refer this link -
http://www.w3schools.com/angular/angular_http.asp
I agree with previous answer. Also its wrong to use $(document).ready along with using angular framework in you application.
Try something like this:
angular.module('sortApp', [])
.service('loadTestCsv' ['$http', function($http) {
return $http.get('test.csv').then(data => {
// do all data processing you need
return data;
});
}]);
.controller('mainController', ['$scope', 'loadTestCsv', function($scope, loadTestCsv) {
loadTestCsv().then(data => {
$scope.data = data;
});
}]);
When i try to run the below example mentioned in the Angular JS timer site, I am getting error:
ng:areq
Bad Argument
Argument 'MyAppController' is not a function, got undefined
http://errors.angularjs.org/1.3.14/ng/areq?p0=MyAppController&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at file:///C:/ICDP/Angular/angular/angular.min.js:6:417
at Sb (file:///C:/ICDP/Angular/angular/angular.min.js:19:510)
at tb (file:///C:/ICDP/Angular/angular/angular.min.js:20:78)
at file:///C:/ICDP/Angular/angular/angular.min.js:75:331
at file:///C:/ICDP/Angular/angular/angular.min.js:57:65
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Example - Multiple Timers 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;
};
}
MyAppController.$inject = ['$scope'];
</script>
</head>
<body ng-app="MyApp">
<div ng-controller="MyAppController">
<h2>AngularJS - Multiple Timers Example</h2>
<h3>Timer 1: <timer/></h3>
<h3>Timer 2: <timer interval="2000"/></h3>
<h3>Timer 3: <timer> minutes, seconds.</timer></h3>
<button ng-click="startTimer()" ng-disabled="timerRunning">Start Timers</button>
<button ng-click="stopTimer()" ng-disabled="!timerRunning">Stop Timers</button>
</div>
</body>
</html>
I have the below two files included
<script src="../angular/angular.min.js"></script>
<script src="../app/js/timer.js"></script>
http://siddii.github.io/angular-timer/examples.html#/plain-javascript-source
Open Chrome developer tools(F12), then open folder with file: angular-timer -> examples -> angularjs-single-timer.html and you will see that (it is just little mistake):
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Example - Single Timer Example</title>
<!-- compiled JavaScript -->
<script type="text/javascript" src="../dist/assets/js/angular-timer-bower.js"></script>
<script type="text/javascript" src="../dist/assets/js/angular-timer-all.min.js"></script>
<script>
angular.module('MyApp', ['timer'])
.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);
});
}]);
</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>
You have not MyAppController Controller. You must tell angular that there is controller named MyAppController. Try this to fix your problem.
angular.module('MyApp', ['timer']).controller('MyAppController', MyAppController);
And link that can be useful https://docs.angularjs.org/guide/controller
For some reason it gives me the error:
ReferenceError: random is not defined at Scope.$scope.generateRandom
I dont know what im doing wrong, you can go check out the website im using to do this HERE.
index.html:
<!DOCTYPE html>
<html lang= "en">
<head>
<meta charset="UTF-8" />
<title>Basic Login Form</title>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src = "https://rawgit.com/nirus/Angular-Route-Injector/master/dist/routeInjector.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.js"></script>
<script type="text/javascript" src="script23.js"></script>
</head>
<body ng-app = "app" ng-controller = "app">
<button ng-click = "generateRandom()">Generate Random Number</button>
<br> {{randomNumber}}
</body>
</html>
script23.js:
var app = angular.module('app', []);
app.service('random', function(){
var randomNum = Math.floor(Math.random()*10)
this.generate = function(){
return randomNum;
}
});
app.controller('app' , function($scope){
$scope.generateRandom = function(){
alert("Something")
$scope.randomNumber = random.generate();
}
})
To use service in controller, you need to inject it.
app.controller('app', function ($scope, random) {
I'd recommend you to use following syntax:
app.controller('app', ['$scope', 'random', function ($scope, random) {
See Why we Inject our dependencies two times in angularjs?
Change your controller like this, since you are using the service 'random'
myApp.controller('app', ['$scope','random', function( $scope,random)
{
$scope.generateRandom = function(){
alert("Something")
$scope.randomNumber = random.generate();
}
}])
Here is the working Application
I would like to open a new tab after $http call. Currently, even-though the call is made after user click, popup blocker doesn't allow new tab to be created.
HTML:
<div ng-controller="ExampleController">
<button ng-click="openNewTab()">Open new tab</button>
</div>
Controller
.controller('ExampleController', ['$scope','$http', function($scope,$http) {
$scope.openNewTab = function(e) {
$http.get("test.com").finally(()=>{
window.open();
});
};
}]);
Plunker
Try this Code to open the new tab call the function
.controller('ExampleController', ['$scope','$http', function($scope,$http,$window) {
$scope.openNewTab = function(e) {
$http.get("test.com").finally(()=>{
$window.open('url','_blank');
});
};
}]);
You can use setInterval out of ajax call where you have to check your variable again and again which will be set in ajax call when condition matches then you can open new tab.
I've also found a workaround for you.
<!DOCTYPE html>
<html ng-app="Demo">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script data-require="jquery#2.0.1" data-semver="2.0.1" src="http://code.jquery.com/jquery-2.0.1.min.js"></script>
<script src="https://code.angularjs.org/1.3.0-beta.9/angular.js"></script>
<script src="demo.js"></script>
</head>
<body ng-controller="DemoCtrl">
<button ng-click="doesntWork()">This Doesn't Work</button>
</body>
</html>
and the angular code:
angular.module("Demo", []).controller("DemoCtrl", function($scope, $http) {
$scope.doesntWork = function() {
var isSuccess=0;
$http.get('https://api.github.com/users/angular').then(function (result)
{
isSuccess=1;
});
var timer = setInterval(function () {
if (isSuccess!= 0) {
clearInterval(timer);
}
if (isSuccess== 1) {
var newWin = $window.open('', '_blank');
newWin.location = "https://www.google.co.in";
}
},1000);
};
});
You can do this by using the $window service. $window is a wrapper around the global browser object window. Maybe this solves your answer too:
Open a new tab on button click in AngularJS
I've also found a workaround for you.
<!DOCTYPE html>
<html ng-app="Demo">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script data-require="jquery#2.0.1" data-semver="2.0.1" src="http://code.jquery.com/jquery-2.0.1.min.js"></script>
<script src="https://code.angularjs.org/1.3.0-beta.9/angular.js"></script>
<script src="demo.js"></script>
</head>
<body ng-controller="DemoCtrl">
<button id="test" ng-click="works()">This Works</button>
<button ng-click="doesntWork()">This Doesn't Work</button>
</body>
</html>
and the angular code:
angular.module("Demo", []).controller("DemoCtrl", function($scope, $http) {
function openInNewTab() {
var uri = 'http://www.google.nl';
var link = angular.element('');
angular.element(document.body).append(link);
link[0].click();
link.remove();
};
$("#test").click(function(){
openInNewTab();
});
$("#test").click();
$scope.works = openInNewTab;
$scope.doesntWork = function() {
$http.get('https://api.github.com/users/angular').then(openInNewTab);
};
});