How to Define Dynamic Functions to an AngularJS Object and Call Functions with ng-Click

← PrevNext →

I have a list of items that I wish to show to my users. That is simple. I’ll create an object in my controller, add few items to it, and finally use an ng-repeat directive to render the list. However, I also want to define a function dynamically to each item in an AngularJS object to call when the user clicks an item.
The Markup and the Script
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
    <style>
        ul { 
            margin:5px 0;
            padding:0;
            cursor:pointer;
            width:150px;
        }
        ul:hover {
            text-decoration:underline;
        }
        li  {
            list-style:none;
        }
    </style>
</head>

<body>
    <div ng-app="myApp"
        ng-controller="myController">

        <h3>Click the Product:</h3>

        <ul ng-repeat="prod in products">
            <li ng-bind="prod.name" id="{{prod.name}}" ng-click="prod.func($event)"></li>
        </ul>

        <p>{{product}}</p>
    </div>
</body>

<script>
    angular.module('myApp', [])
        .controller('myController', ['$scope', function ($scope) {

            $scope.products = [
                { name: 'iPhone 6', func: checkProd },
                { name: 'Micromax Canvas', func: checkProd },
                { name: 'Samsung Galaxy', func: checkPrice }
            ];

            // FIRST FUNCTION.
            function checkProd(e) {
                angular.forEach($scope.products, function (value, key) {
                    if ($scope.products[key].name == e.target.id)
                        $scope.product = 'You chose - ' + $scope.products[key].name;
                });
            };

            // SECOND FUNCTION.
            function checkPrice() {
                $scope.product = 'Price is 10x';
            };
        } ]);
</script>
</html>
Try it

The ng-repeat directive (in the markup section) loops through each item that I have defined in the products object (in the controller).

$scope.products = [ …

The object has two properties. The name: property has a list of items (smart phones) and the func: property has function names to call when clicked using ng-click directive.

Look carefully, the first two item calls the first function named checkProd(e) (takes a parameter as event) and the last item calls the second function. You can associate each item with different functions. You can now use the function to extract more data from any data source using the selected item.

← PreviousNext →