Attaching Behaviour ( methods) to the Controller in AngularJS

You can attach multiple methods or behaviour to the controller via $scope object.


The following example demonstrates the concept of attaching behaviour to the controller.


In the below code snippet, sum property of the $scope is set to the function that returns sum of 3 and 5. When the page loads, the sum function is called that returns sum of 3 and 5, the returned value is written at placeholder {{ }}.

You can attach multiple methods or behaviour to the controller via $scope object.


The following example demonstrates the concept of attaching behaviour to the controller.


In the below code snippet, sum property of the $scope is set to the function that returns sum of 3 and 5. When the page loads, the sum function is called that returns sum of 3 and 5, the returned value is written at placeholder {{ }}.



Important Note

Notice the second parameter of the controller() has been written wrapped with square bracket [ ] and first parameter we have passed is '$scope' as string parameter and then the function definition is written.Instead of this, we could have also defined the controller like given below.

app.controller('myController', function($scope) {
    // code goes here
});

However, the first approach (in the first code snippet) is recommended. As when we deploy our application, we use bundling and minification and these tools changes the name of the long variables to short.


Passing arguments to controller methods in AngularJS

In the above example, we have declared two function, Country and countryCulture. The Country function accepts only one parameter (name) whereas countryCulture function accepts two parameters (name and culture).

On click on first three buttons, we called Country method with only one parameter however on click on 4th button, we called countryCulture method and passed two parameters .






References :- AngulaJS Documentation



Related Articles

  1. Maven Overview




comments powered by Disqus