Pulse7
9/9/2017 - 9:37 AM

Multiple controllers example

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
    <script src="app.js"></script>
    <script src="CountdownController.js"></script>
    <script src="UserController.js"></script>
</head>
<body ng-app="App">
    <div ng-controller="CountdownController">
        <h1>{{countdown}}</h1>
        <button ng-click="stopCountdown()">Stop</button>
        <button ng-click="resetCountdown()">Reset</button>
        <button ng-click="startCountdown()">Start</button>
    </div>
    <div ng-include="'user.html'">

    </div>
</body>
</html>

(function () {
    let UserController = function ($scope) {
        $scope.name="Bob";
        $scope.img="avatar.png";
    }

    let module = angular.module("App");
    module.controller("UserController", UserController);
})()
(function () {
    let CountdownController = function ($scope, $interval) {
        let intervalToken;
        const countdownStartNumber = 5;
        const countdownEndAction = function () {
            console.log("Countdown ended");
        }
        const decrementCountdown = function () {
            $scope.countdown--;
            if ($scope.countdown < 1)
                countdownEndAction();
        }
        $scope.resetCountdown = function () {
            $scope.stopCountdown();
            $scope.countdown = countdownStartNumber;
        }
        $scope.startCountdown = function () {
            if (stopped) {
                intervalToken = $interval(decrementCountdown, 1000, $scope.countdown);
                stopped = false;
            }
        }
        $scope.stopCountdown = function () {
            stopped = true;
            $interval.cancel(intervalToken);
        }
        $scope.countdown = countdownStartNumber;
        let stopped = true;
        $scope.startCountdown();
    }

    let module = angular.module("App");
    module.controller("CountdownController", CountdownController);
})()
(function () {
    angular.module("App", []);
})();
<div ng-controller="UserController">
    <h1>{{name}}</h1>
    <img src="{{img}}">
</div>