Alternative approach for multiple button click in angularjs


I am just wondering is there any better way to approach same kind of logic as below. 4 buttons onclick of it have to send parameters like (english, german, spanish, french) to angular function. Is there any possibility to reduce repetition of code here by using model binding or array or enum??

Even following approach may or may not be the best way to handle it. Since I am not that proficient in angular I am not sure about better alternative approach. Please advice.

Basically is there any way to implement same logic in a better way??

Note: I am using angular 1.7.2 version

<!DOCTYPE html>
            <script src=""></script>

                    var app = angular.module('app', []);
                    app.controller('myController', ['$scope', function($scope) {
                    $scope.Language = 'German';
                        $scope.Preference = function(lang) {
                           $scope.Language = lang;

                    <h2>Attach functions or behavior - AngularJS</h2>
                <div ng-app="app" ng-controller="myController">
                <button ng-click="Preference('English')">English</button>
        <button ng-click="Preference('German')">German</button>
        <button ng-click="Preference('Spanish')">Spanish</button>
        <button ng-click="Preference('French')">French</button>
                <p>I like {{ Language}}</p>


You can use ng-repeat for the buttons and an array for the values. Also you can avoid using function by using ng-click to set the selected value:

<button ng-repeat="lan in vm.languages" ng-click="vm.Preference(lan)">{{lan}}</button>

Check a demo: DEMO

Answered By – Bill P

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.