Angular JS Magazine

luni, 15 septembrie 2014

Service and Scope Events

In Communicating Between Scopes you saw how two views in the application can communicate even if they use the same controller. In this tip we have added an Angular JS service, which is capable to mediate the communication between scopes. In this case, the service is not mandatory to be used, but is more like an Angular JS convention:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="../angular/angular.min.js"></script>
    <script>
        angular.module("appModule", [])
                .service("UpdateCounter", function ($rootScope) {
                    return {
                        setCounter: function (type, counter) {
                            $rootScope.$broadcast("counterAorBWasUpdated", {
                                type: type, counter: counter
                            });
                        }
                    }
                })
                .controller("atpCtrl", function ($scope, UpdateCounter) {
                    $scope.counter = 0;

                    $scope.increaseCounter = function (type) {
                        $scope.counter = $scope.counter + 1;
                        UpdateCounter.setCounter(type, $scope.counter);
                        console.log("Type: " + type + " Value:" + $scope.counter);

                    }

                    $scope.$on("counterAorBWasUpdated", function (event, args) {
                        $scope[args.type] = args.counter;
                    });

                    $scope.sumCounter = function () {
                        $scope.A = $scope.A || 0;
                        $scope.B = $scope.B || 0;
                        return $scope.A + $scope.B;
                    }
                });
    </script>
</head>
<body ng-app="appModule">
<div ng-controller="atpCtrl">
    Counter A value: {{counter}}
    <br/>
    Total A + B: {{sumCounter()}}
    <button class="btn btn-primary" ng-click="increaseCounter('A')">
        Increase Counter A
    </button>
</div>
<hr/>
<div ng-controller="atpCtrl">
    Counter B value: {{counter}}
    <br/>
    Total A + B: {{sumCounter()}}
    <button class="btn btn-primary" ng-click="increaseCounter('B')">
        Increase Counter B
    </button>
</div>

</body>
</html>