Angular JS Magazine

sâmbătă, 13 septembrie 2014

Reusing a Controller

The same controller can be used in different views of the same application. The factory function will be called to create a separate controller with its own scope:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="../angular/angular.min.js"></script>
    <script>
        angular.module("atpModule", [])
                .controller("atpCtrl", function ($scope) {
                    $scope.counter = 0;

                    $scope.increaseCounter = function (type) {
                        $scope.counter = $scope.counter + 1;
                        console.log("Type: " + type + " Value:" + $scope.counter);
                    }
                });
    </script>
</head>
<body ng-app="atpModule">
<div ng-controller="atpCtrl">
    Counter A value: {{counter}}
    <button class="btn btn-primary" ng-click="increaseCounter('A')">
        Increase Counter A
    </button>
</div>
<hr/>
<div ng-controller="atpCtrl">
    Counter B value: {{counter}}
    <button class="btn btn-primary" ng-click="increaseCounter('B')">
        Increase Counter B
    </button>
</div>

</body>
</html>


And the console output is:



Niciun comentariu:

Trimiteți un comentariu