AngularJS > Controllers

Attaching methods in AngularJS

How to attach methods/behavior to the controller in AngularJS?


To attach methods or behavior to the controller, we add them via $scope object.

    <script>
        var app = angular.module('app', []);
        app.controller('myController', ['$scope', function($scope) {
            $scope.Square = function(val) {
                return 2 * 2;
            };
        }]);
    </script>

    <h2>Attach functions or behavior - AngularJS</h2>
    <div ng-app="app" ng-controller="myController">
        Square of
2
        is {{ Square() }}        
    </div>

In the above code snippet, Square property of the $scope is set to the function that returns square of 2. When the page loads, the Square function is called that returns square of 2 and the returned value is written at placeholder {{ }}.

Important:

Notice the 2nd parameter of the app.controller that has been written wrapped with square bracket [ and ], here we have passed '$scope' as string parameter and then the function definition is written.

Instead of this, we could have also defined the controller like

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. However, these tools doens't touch data that is written as string. So after bundling and minification, AngularJS still knows that the shorter variables is nothing but the variable that is written in the string.

If we need to pass more than one parameter to the function, we write those parameter name as string in the same order as it exists in the function definition.

 Views: 12918 | Post Order: 17




Write for us






Hosting Recommendations