2

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 ?

2
  • Unfortunately, your question is too broad. Instead of asking about every possible option available to you in this situation, you might ask about a specific thing you are trying to do, or specific code that you have tried to use that you are confused about. You will get better answers that way, and we won't be re-writing an entire documentation section. Commented Jan 14, 2017 at 21:00
  • Okay but I am just getting started with it so I just want to have clear view on which code I will write is best practice or not. Commented Jan 15, 2017 at 9:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks !! It's really helpful

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.