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>
<html>
<head>
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('myController', ['$scope', function($scope) {
$scope.Language = 'German';
$scope.Preference = function(lang) {
$scope.Language = lang;
};
}]);
</script>
</head>
<body>
<h2>Attach functions or behavior - AngularJS</h2>
<div ng-app="app" ng-controller="myController">
Click
<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>
</div>
</body>
</html>
You can use
ng-repeatfor the buttons and an array for the values. Also you can avoid using function by usingng-clickto set the selected value:Check a demo: DEMO