Zet Zet - 13 days ago 7
Javascript Question

simple angular function explanation needed

I created a simple angular function. The purpose is to display a changing value of variable x after pressing a button which triger the function startAction. It is not working and I have no idea why.

var app = angular.module("myApp", []);
app.controller('myController', ($scope, fabryka) => {

$scope.startAction = function () {
setInterval(function () {
var x = 0;
$scope.x = (function () {
x++;
return x;
})();
}, 500);
}
});

Answer

Angular has its own setInterval wrapper: $interval.

This piece of code counts seconds as you press the button. Please note the interval cancellation when the scope is destroyed.

angular.module('app', [])
  .controller('mainCtrl', function($scope, $interval) {
    var vm = this;

    vm.x = 0;

    var interval;

    vm.startAction = function() {
      vm.isRunning = true;
      interval = $interval(function() {
        vm.x++;
      }, 1000);
    };

    vm.stopAction = function() {
      vm.isRunning = false;
      $interval.cancel(interval);
    }

    $scope.$on('$destroy', vm.stopAction);

    return this;
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="mainCtrl as vm">
  <div>x: {{vm.x}}</div>
  <button ng-click="!vm.isRunning? vm.startAction():vm.stopAction()">{{vm.isRunning? 'Pause':'Start'}}</button>
</div>