Having a similar requirement, I encountered a situation in my Ionic form where I needed to set values for 6 fields of the same type/data by clicking a button without duplicating the function in the controller. I wanted to call a function on button click, passing the field (ng-model) name as a parameter, which initially wasn't working. After some trial and error, I managed to get it to work. It took me a while to figure it out since I'm still new to Angular/Ionic. Hopefully, this solution can assist others who may be facing a similar challenge.
Here is an example of the first couple of fields:
<div class="item item-input-inset">
<label class="item item-input-wrapper">
<i class="icon ion-edit placeholder-icon"></i>
<input type="text" placeholder="00:00" ng-model="formdata.time1">
</label>
<button class="button" ng-click="settime('time1')">Now</button>
</div>
<div class="item item-input-inset">
<label class="item item-input-wrapper">
<i class="icon ion-edit placeholder-icon"></i>
<input type="text" placeholder="00:00" ng-model="formdata.time2">
</label>
<button class="button" ng-click="settime('time2')">Now</button>
</div>
Corresponding controller code:
.controller('YourCtrl', function ($scope) {
$scope.formdata = {};
$scope.settime = function(field){
var d = new Date();
$scope.formdata[field] = d.getUTCHours()+':'+(d.getUTCMinutes() < 10 ? '0'+d.getUTCMinutes():d.getUTCMinutes());
}
});
If you need to pass a value from a button, you can include a parameter:
<div class="item item-input-inset">
<label class="item item-input-wrapper">
<i class="icon ion-edit placeholder-icon"></i>
<input type="text" ng-model="formdata.yourfield">
</label>
<button class="button" ng-click="yourfunction('This Value','yourfield')">This</button>
<button class="button" ng-click="yourfunction('That Value','yourfield')">That</button>
</div>
And likewise in the controller:
.controller('YourCtrl', function ($scope) {
$scope.formdata = {};
$scope.yourfunction = function(value,field){
$scope.formdata[field] = value;
}
});