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>
<head lang="en">
    <meta charset="UTF-8">
    <script src="../angular/angular.min.js"></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);
<body ng-app="atpModule">
<div ng-controller="atpCtrl">
    Counter A value: {{counter}}
    <button class="btn btn-primary" ng-click="increaseCounter('A')">
        Increase Counter A
<div ng-controller="atpCtrl">
    Counter B value: {{counter}}
    <button class="btn btn-primary" ng-click="increaseCounter('B')">
        Increase Counter B


And the console output is: