AngularJS > Controllers

Passing arguments to controller methods in AngularJS

How to pass arguments to controller methods in AngularJS?


To pass arguments to the controller method, we need to define them with those number of arguments and while calling them, we need to call them with that number of arguments.


    <script>
        var app = angular.module('app', []);
        app.controller('myController', ['$scope', function($scope) {
        $scope.Language = 'Hindi';
            $scope.Preference = function(lang) {
               $scope.Language = lang;
            };    

            $scope.Preference1 = function(lang, lang1) {
               $scope.Language = lang;
         $scope.Language1 = lang1;
            };    
        }]);
    </script>

   <h2>Attach functions or behavior with arguments - AngularJS</h2>
    <div ng-app="app" ng-controller="myController">
    Click
    <button ng-click="Preference('English')">English</button>
    <button ng-click="Preference('Hindi')">Hindi</button>
    <button ng-click="Preference('Spanish')">Spanish</button>
    <button ng-click="Preference1('French', ' and Hindi language also.')">French</button>
    <p>I like {{ Language}} language {{ Language1 }} </p>
    </div>

In the above code snippet, we have declared two function, Preference and Preference1. The Preference function accepts only one parameter (lang). The Preference1 function accepts  two parameters (lang and lang1).

On click on first three buttons, we call Preference method with only one parameter (language name - English, Hindi etc.) however on click on 4th button, we have called Preference1 method and passed two parameters 'French' and ' and Hindi language also'.

output

 Views: 75871 | Post Order: 18




Write for us






Hosting Recommendations