AngularJS: making a simple stopwatch, a little confused - angularjs

Here's the code so far: http://plnkr.co/edit/DK9SSrIJZieSxDb5EN41?p=preview
Goal: press the start button and the seconds counter begins.
cant seem to get it working, the CountdownCtrl function should only start when button clicked.. so do i have two seperate functions, or how do i go about doing this.

My fork of your plunk shows how to do this. Check it out. I simplified your original code to show how you can make this easier to understand and to maintain.
First thing, you needed to initialize your module correctly.
var myApp = angular.module('myApp', []); // the second param is your module's dependencies. since you have none, it MUST be an empty array
Next, declare your controller, and take in two dependencies, the $scope and $timeout:
myApp.controller('CountDownCtrl', ['$scope', '$timeout', function($scope, $timeout) { // angular will inject the controller's $scope and the $timeout service
// todo
}]);
Then, declare an item on the $scope to store the counter value. This value will be accessible in the view. Then define a function to perform the actual countdown. It simply increments $scope.value and then sets a new timeout to itself, in effect calling itself every second until it is canceled.
Finally, add functions to start and stop the countdown:
$scope.value = 0;
// because of JS closures, $scope from the outer context will be included in countdown()'s context.
function countdown() {
$scope.value++;
$scope.timeout = $timeout(countdown, 1000);
}
$scope.start = function() {
countdown();
};
$scope.stop = function() {
$timeout.cancel($scope.timeout);
};
Lastly, make sure your view instructs it what controller to use and add in the appropriate controller functions.
<body ng-controller="CountDownCtrl">
{{value}}
<button ng-click="start()">Start</button>
<button ng-click="stop()">Stop</button>
</body>

You were definitely on the right track. There were just a few things that weren't wired up.
Here is an updated plunker.
These are the main things that were needed to get everything working:
Defined 'myApp' as the name of the module and wired up. This allows controller to be registered correctly to the module.
Make CountDownCtrl function a scoped function.
Set up of the dependencies $timeout was moved to be registered against the controller (not the function).
HTML:
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="m">
{{value}}
<button ng-click="CountDownCtrl()">Start</button>
</body>
</html>
JS:
var myApp = angular.module('myApp', []);
myApp.controller('m', ['$scope', '$timeout', function($scope, $timeout) {
$scope.value = 0;
$scope.CountDownCtrl = function() {
$scope.value = 0;
var change = function() {
$scope.value += 1;
$timeout(change,1000);
};
$timeout(change, 1000);
}
}]);

Related

AngularJS - two way binding not working using service

I am learning Angular using W3Schools.
I just modified an example about "Services"... The following is the code:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p><input type="text" ng-model="num"></p>
<h2>{{num}}</h2>
<h1>{{hex}}</h1>
</div>
<p>A custom service whith a method that converts a given number into a hexadecimal number.</p>
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.hex = hexafy.myFunc($scope.num);
});
</script>
</body>
</html>
When I update the textbox, the "HEX" part is not updating. Why?
Your hexafy.myFunc is called only once when the controller is initialized, hence only the initial value is converted to hex. If you want a function to be called on the value change of a scope variable in runtime, you need filters. AngularJS has a lot of inbuilt filters that are ready to use.
You can also define a custom filter, just like you define services or controllers.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p><input type="text" ng-model="num"></p>
<h2>{{num}}</h2>
<h1>{{num | hexafy}}</h1>
</div>
<p>A custom filter that converts a given number into a hexadecimal number.</p>
<script>
var app = angular.module('myApp', []);
app.filter('hexafy', function() {
return function (x) {
return Number(x).toString(16); // Also convert the string to number before calling toString.
}
});
app.controller('myCtrl', function($scope) {
$scope.num = 200;
//$scope.hex = hexafy.myFunc($scope.num);
});
</script>
</body>
</html>
Further reading: AngularJS Filters
NOTE: A filter is a good idea if you're gonna be using the hexafy functionality at multiple places in/across views. Otherwise, it is just an overkill and the $scope.$watch method will work fine for you, as described in other answers
$scope.hex is not updating because there're no way for it update itself.
The hexafy.myFunc is called only once when the controller is loaded for the first time.
If you want want the $scope.hex property to change with num, you might need a watch on the num property.
$scope.$watch('num', function(newVal, oldVal) {
$scope.hex = hexafy.myFunc($scope.num); /// or newVal
}
The function passed in $scope.$watch will be called everytime the value of $scope.num changes.
for more info see https://docs.angularjs.org/api/ng/type/$rootScope.Scope (the watch section)
Hope it helps.
No need of a service here, you can simple use $watch on the num. See below code snippet, it will update your ui, I have updated your controller code, please check.
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.hex = "some default val";
$scope.$watch('num', function(newValue, oldValue) {
$scope.hex = newValue.toString();
});
});
Your Text box is only bind to 'num'. '$scope.hex is not binded to your text box'. So that it is not update when you typing text. You could use '$watch' on 'num'. Read here
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.$watch('num', function() {
$scope.hex = hexafy.myFunc(parseInt($scope.num));
});
});

View is not updated after the $http async call when using controllerAs syntax

I am learning angularjs and I am trying to use the controllerAs syntax as I am from Java background and this would make more sense to me but I am having trouble understanding the digest loop.
I am trying to do a http call and update the variable in the controller.When I am using $scope in controller the view is updated after the data is received but when I am using the controllerAs syntax the view is not updated.
Codepen with $scope Syntax
http://codepen.io/eternal15/pen/BzANEw?editors=1111
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.min.js"></script>
</head>
<body ng-app="Test" ng-controller="testCtrl">
{{output}}
<button ng-click="onClick()">Test</button>
</body>
</html>
//JS FILE
angular.module("Test", []).controller('testCtrl', ['$scope','$http', function($scope, $http){
$scope.output = "Loading";
$scope.onClick = function(){
console.log('clicked');
$http.get('http://jsonplaceholder.typicode.com/posts').then(function(data){
$scope.output = "worked!!";
console.log($scope.output);
})
}
}]);
Codepen with controllerAs Syntax (View not updated)
http://codepen.io/eternal15/pen/yJKoaZ?editors=1011
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.min.js"></script>
</head>
<body ng-app="Test" ng-controller="testCtrl as test">
{{test.output}}
<button ng-click="test.onClick()">Test</button>
</body>
</html>
//JS File
angular.module("Test", []).controller('testCtrl', ['$http', function($http){
this.output = "Loading";
this.onClick = function(){
console.log('clicked');
$http.get('http://jsonplaceholder.typicode.com/posts').then(function(data){
this.output = "worked!!";
console.log(this.output);
})
}
}]);
I have read about the controllerAs syntax and I think it would add the object (test in the example above) under scope and thus the variables are accessible using (test) object.
So the digest loop runs after $http call because the view is updated in the first example using $scope. Since the digest loop is executed the object test in the second example should also be updated right?
Also i tried to inject $scope and do $scope.$apply() and that also didn't work and it gave me this error
Error: [$rootScope:inprog] http://errors.angularjs.org/1.5.2/$rootScope/inprog?p0=%24digest
I would like to know what I am doing wrong. Although i could go back to using the $scope format, I would like to know if I am doing something wrong or should I add other statements to watch the variables and update the values manually.
Thanks in advance
this has a different meaning inside function. Assign this to a variable and use it. Try:
angular.module("Test", []).controller('testCtrl', ['$http', function($http){
var vm = this;
vm.output = "Loading";
vm.onClick = function(){
console.log('clicked');
$http.get('http://jsonplaceholder.typicode.com/posts').then(function(data){
vm.output = "worked!!";
console.log(vm.output);
})
}
}]);
This is because of javascripts closures. When defining a new function you're creating a new scope, hence the keyword this has a new meaning for each new scope.
To solve this, define the controllers scope at the top of your controller. Common names used are either vmor $ctrl.
Your controller would then look somehting like this:
angular.module("Test", []).controller('testCtrl', ['$http', function( $http){
var $ctrl = this;
$ctrl.output = "Loading";
$ctrl.onClick = function(){
console.log('clicked');
$http.get('http://jsonplaceholder.typicode.com/posts').then(function(data){
$ctrl.output = "worked!!";
//$scope.$apply();
})
}
}]);

Change ng-show in another controller?

I want to change ng-show in another controller than ng-show is.
myApp.controller('popupCtrl', function() {});
myApp.controller('changePopup', function($rootScope){
// now i wanna show my Ppopup
$rootScope.popup = true;
});
<div ng-controller="popupCtrl">
<div ng-show="popup">
Popuptext
</div>
</div>
But this doesn't work... How can I fix it?
Thanks!
So first thing, you should never add to the $rootScope or change it in anyway. It has been optimised by the angular team.
Second thing, there is no need to involve the $rootScope.
Here is a demo showing how to communicate across two controllers.
The key is the event aggregator pattern:
Communicator.register(function (newValue) {
vm.value = Communicator.value;
});
I created a function in the Communicator to register a callback function. The aim is that when a value gets changed the callback function is fired off. I.e. an event is triggered (change event).
The second key part is fire that change event off:
Communicator.change(!Communicator.value);
Here we pass through to the change function a new value which will do two things:
Update the internal value so we can keep track of it
Loop through all the registered callbacks and execute them passing in the new value.
By implementing this pattern, we can minimise the extent to which we communicate around our application ($rootScope can have a tendency to traverse the scope heirarchy when you $broadcast).
Now we can follow more closely the principle of single responsibility. Our class is aptly named in its current scope, when we look at this factory we can tell it is supposed to "communicate".
Finally, with a global event aggregator pattern ($rootScope) it is far more difficult to keep track of where these events are being broadcast from, and where they'll end up. Here we don't have that issue
One way to solve this is to use $rootScope.$broadcast
Here is an example: http://plnkr.co/edit/EmJnZvXFRWv6vjKF7QCd
var myApp = angular.module('myApp', []);
myApp.controller('popupCtrl', ['$rootScope', '$scope', function($rootScope,$scope) {
$scope.popup = false;
$rootScope.$on('changePopup', function(event, data) {
$scope.popup = !$scope.popup;
});
}]);
myApp.controller('changePopup', ['$rootScope', '$scope', function($rootScope, $scope) {
$scope.changePopup = function() {
$rootScope.$broadcast('changePopup', 'data could be sent here');
}
}]);
View:
<div ng-controller="popupCtrl">
<div ng-show="popup">
Popuptext
</div>
<div ng-controller="changePopup">
<button ng-click="changePopup()">Change the popup</button>
</div>
Using a service/factory is a better solution for cross controller communication if you are working on a large application, but for a smaller app I would say using $broadcast, $emit and $on is sufficient.
Here is a working demo for you - sorry I changed the controller names, but I am sure you will be able to build on this. Good luck
angular.module('myApp', [])
.controller('c1', function($scope) {
// now i wanna show my Ppopup
$scope.popup = false;
$scope.$on('popup', function() {
$scope.popup = true;
});
})
.controller('changepopup', function($rootScope, $scope) {
// now i wanna show my Ppopup
$scope.clicker = function() {
$rootScope.$broadcast('popup')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="c1">
<div ng-show="popup">
Popuptext
</div>
</div>
<button ng-controller="changepopup" ng-click="clicker()">Click me</button>
</div>

AngularJS: How can I assign values to main page from templates and show them?

In my mine file I have the div with ng-view and it is loaded with the some template. Inside the temp`late I have a button which will change the value.
after to click the button, I am trying to show the value in the index but I recieving a null value.
In index.html I could have something like:
<html>
...
<body ng-app="productsApp" ng-Controller="mycontroller">
<div ng-view></div>
{{value}}
</body>
</html>
In my controller I have something like
angular.module('productsApp').controller('ProductController',
['$scope', 'dataService', function ($scope, dataService) {
$scope.value;
$scope.button = function () {
$scope.value= "123";
};
}]);
The template could be something like:
<button ng-click="button">CHANGE</button>
How can I assign values to main page from templates and show them?
You need to beware which controller you set, the names have to match. Also beware of typos, even when typing fast ;). Also look into the function call. You forgot to use () at the end. And naming things a little bit better would be recommended to (I don't say my namings are the best, but calling a function button is not very readable).
HTML
<body ng-controller="MainCtrl">
<p>Value {{value}}!</p>
<button ng-click="btnPressed()">Change</button>
</body>
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.value = "456";
$scope.btnPressed = function() {
$scope.value = 123;
}
});
The controllers name in this example is MainCtrl. You need to refer the correct name as well in your HTML (you mix mycontroller and ProductController).
Working Plnkr
http://plnkr.co/edit/tpl:8rFfZljYNl3z1A4LKSL2
You have defined $scope.button in ProductController which set $scope.value.
But this $scope.value is come under scope of ProductController and not available under scope of mycontroller which parent scope.Thats why you getting null value.
Define $scope.value and $scope.button in mycontroller.
Or better way is define this functionality in some factory and access it wherever needed.
Or define that function and variable in $rootScope like
$rootScope.value;
but it make this global.
or define like this
$scope.$parent.value;

Why doesn't ng-hide/show work if expression is a scope variable modified on broadcast event

I have the following code:
script.js:
var app = angular.module('TestApp',[]);
app.factory('testfactory', function($rootScope, $window){
var factory = {};
factory.auth = function() {
//This is only to make call to auth() async.
//Actual code is using google-api call.
setTimeout(auth, 2000);
}
$window.auth = function(){
$rootScope.$broadcast('loggedin');
}
return factory;
});
app.controller('MainCtrl', function($scope, testfactory) {
$scope.status = {
loggedIn: false
}
$scope.test = testfactory;
$scope.$on('loggedin', function(){
$scope.status.loggedIn = true;
alert('loggedIn');
});
});
index.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body ng-app="TestApp">
<div ng-controller="MainCtrl">
<button ng-click="test.auth()" ng-hide="status.loggedIn">Auth</button>
</div>
<script data-require="angular.js#1.2.19" data-semver="1.2.19" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="script.js"></script>
</body>
</html>
This should hide the button "Auth" on clicking, however it does not. It works only when its clicked the second time. What's happening here? I'm modifying the scope variable inside angular's broadcasted event, so binding should work. What am I missing here?
Edit: I know wrapping the code within $scope.$apply works, but my question is why isn't it happening automatically, since I'm not modifying the variable from outside the scope.
Here's a plunker for this code - http://plnkr.co/edit/Ov568VDWCKarFHQjgbvG
Answer: This discussion on google groups says $broadcast doesn't trigger auto-apply. So, if $broadcast is called from outside of angular-world, $apply must be applied manually.
Because Angular use $digest (documentation, and why/where to use) to keep the binding between the $scope and the interface. Try to force the $digest:
$scope.$on('loggedin', function(){
$scope.status.loggedIn = true;
$scope.digest();
alert('loggedIn');
});
or
$scope.$on('loggedin', function(){
$scope.apply(function(){
$scope.status.loggedIn = true;
});
alert('loggedIn');
});
Edit:
why isn't it happening automatically ?
The setTimeout function runs outside the angular scope, therefore angular has no idea that you might change something.
You could also solve the problem with the #pixelbits solution. The $timeout service is just a wrapper around javascript's setTimeout witch executes within the angular scope.
http://plnkr.co/edit/o3XtMLpCquHcU2j2z4v9?p=preview
please add $scope.$apply();
app.controller('MainCtrl', function($scope, testfactory) {
$scope.status = {
loggedIn: false
}
$scope.test = testfactory;
$scope.$on('loggedin', function()
{
$scope.status.loggedIn = true;
$scope.$apply();
alert('loggedIn');
});
});
Use $timeout instead of setTimeout. $timeout will trigger a $digest cycle, but setTimeout will not:
$timeout(auth,2000);

Resources