Dip Parmar
Dip Parmar

Reputation: 312

how to react on event in AngularJS Controller

From Official Site: https://docs.angularjs.org/guide/controller

Adding Behavior to a Scope Object In order to react to events or execute computation in the view we must provide behavior to the scope. We add behavior to the scope by attaching methods to the $scope object. These methods are then available to be called from the template/view.

Questions 1. Which events and how to react in controller? 2. Can I do complex and lengthy computation in the controller or not ?

Upvotes: 2

Views: 327

Answers (1)

Kees van Lierop
Kees van Lierop

Reputation: 1013

1. Which events and how to react in controller?

With events, simple interactions are meant with which some data manupilations are involved.

For instance, you could have the following controller:

<div ng-controller="SampleController">

    <p>{{ number }}</p>

    <button ng-click="increment()">Increment the number</button>

</div>

<script>

    var myApp = angular.module('myApp',[]);

    myApp.controller('SampleController', ['$scope', function($scope) {

        $scope.number = 1;

        $scope.increment = function() {

            $scope.number++;

        });

    }]);

</script>

So the event in this case is the click functionality on the button and the action is the data manipulation of the number variable.

2. Can I do complex and lengthy computation in the controller or not ?

You can. But you shouldn't.

A controller is a blank module which you can structure the way you like. But I advise you to avoid this as much as possible.

To prevent duplicate and redundant code, you should combine code that is relevant across multiple controllers into services or factories. With this you can keep your controllers structured, flexible and readable.

Upvotes: 1

Related Questions