Utilize ng-model as a parameter in a ng-click function

Is it possible to pass an ng-model as a function parameter? For example:

<input type="text" ng-model="myModel">
<button ng-click='save('button1', myModel)'>save</button>
<button ng-click='save('button2', myModel)'>save</button>
<button ng-click='save('button3', myModel)'>save</button>


....

var save = function(buttonIndex, myModel){
   myModel = buttonIndex + ' clicked';
}

....

In this particular scenario, there are more than six sets of ng-models present. Instead of creating multiple similar save functions in the controller with only the model being different, I aim to create a single save function by passing the model as a parameter.

Answer №1

If your model is already stored in the $scope, you can access it directly. Otherwise, you can create a function within your controller like so:

$scope.submit = function(model) {
// implement your logic here
}

For example, check out this

demo on using ng-click with arguments
.

Answer №2

Looking for a quick and simple solution for small tasks? Check out this easy method:

<input type="text" ng-model="myModel">
<button ng-click="myModel='button1 clicked'">save1</button>
<button ng-click="myModel='button2 clicked'">save2</button>
<button ng-click="myModel='button3 clicked'">save3</button>

This approach doesn't involve passing parameters, but you can still include regular code in the on-click function.

Check out the demo here!

Answer №3

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;
  }

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Best practices for declaring variables in ReactJS

I need help understanding how to declare a variable in a React JS class so that it is accessible in different functions. Here is my code snippet: class MyContainer extends Component { constructor(props) { super(props); this.testVariable ...

Cookie parsing functionality in Node JS malfunctioning

Currently, I am working through a tutorial on cookie management in Express JS found at . The goal is to implement cookies in my web application to authenticate requests to an API that I am constructing with Node JS. To set the cookie upon user login, I emp ...

I am having trouble with my jQuery wrap function and it is not functioning correctly

I'm having trouble with implementing the jQuery wrap function. (function ($) { $.fn.customWrap = function () { applyWrapper(this); return this; }; function applyWrapper($element) { var $input = $('<input&g ...

Media publications do not conform to the current trends

I'm currently utilizing the HTML-to-paper plugin to print my content on a printer. However, I've encountered an issue where it doesn't seem to apply any of the styles I've defined within @media print. The challenges I'm encounteri ...

How can I access a nested FormArray in Angular?

I have a situation where I am trying to access the second FormArray inside another FormArray. Here is an excerpt from my component: registrationForm = new FormGroup({ registrations: new FormArray([this.patchRegistrationValues()]) }); patchRegistrati ...

Centralized and standardized approach to invoking a function

Explaining this concept may be a bit challenging, but I'll give it a shot: Within the .boxes class div, there are looped elements with the class .box. Each .box element contains two child elements: one with the class .box-header and another with the ...

What changes occurred to module file names following the process of minification?

I'm currently troubleshooting an issue with this particular code snippet: import globalComponents from './global-components'; // ... globalComponents.forEach((component) => { // eslint-disable-next-line no-underscore-da ...

Obtain the URL link from Unsplash where the picture is sourced

As I work on a website, I incorporate a link () to display a random photo. However, the photo refreshes periodically and upon loading the site, all that is visible is this default link: . Is there a method to extract the actual source like so: "". Althou ...

Add transparency to the background color when hovering over inline elements

Initially, my style sheet had the following structure: .button { border-radius: 3px; display: inline-block; padding: 14px 20px; transition: background-color cubic-bezier(0.4, 0.0, 0.2, 1.0) 300ms; &:hover { background-color: transparent ...

Restrict the hide/show functionality on a div to only operate within its specific radio group, without impacting the other radio groups within the form

I created a form with 3 radio groups that show different sets of divs based on the selection made. The issue I'm facing is that the current code hides radio content divs across all 3 radio groups. How can I fix this? My goal is to display all "Yes" c ...

Rails 4 application encountering issues with rendering views when making a $.ajax request

I am a beginner in Rails and I am in the process of sending model data to a controller method from JavaScript for rendering a list of results... function submitResults() { resultURL = "/result"; resultData = JSON.stringify(results); $.ajax({ typ ...

javascript if condition not executing properly

I am struggling with my random number generator that should generate numbers between 5 and 15. I am trying to change the position of the 'chest' div based on the number generated by the computer, but for some reason it is not working as expected. ...

comprehending the concept of automatic refreshing of a webpage using javascript

Can someone help me decipher the following code snippet? function setIdle(cb, seconds) { var timer; var interval = seconds * 1000; function refresh() { clearInterval(timer); timer = setTimeout(cb, i ...

What is the best way to extract a substring separated by two line breaks using a specific index?

Consider having the following string: Apple Banana Pear Pineapple Grapefruit Kiwi Lime Lemon Cherry If I am interested in extracting the line: Pineapple Grapefruit Kiwi how can I achieve this by identifying any index within the second line and locatin ...

When working with Vue CLI, variables defined inside the data property will not function properly if referenced using `this.VariableName`

Issue I am facing an issue where I want to utilize a variable in both the mounted() and methods: sections of my Vue project. I defined the variable in the data() property within the export default {}, but despite no errors being reported, the variable doe ...

Implementing Material-UI Autocomplete: How to Include a Starting Value for the startAdornment

I am using autocomplete with multiple selection permission. https://codesandbox.io/s/bold-jackson-dkjmb?file=/src/App.js In the provided example, there are 3 options for cities. How can I manually insert a value in TextField that is automatically selected ...

What is the best way to customize the styles of Material UI V5 Date Pickers?

Attempting to customize Mui X-Date-Pickers V5 through theme creation. This particular component is based on multiple layers. Interested in modifying the borderColor property, but it's currently set on the fieldset element, so need to navigate from Mu ...

How can I import tamplateData into my JavaScript files in Docpad?

Looking for a DocPad plugin that can preprocess JS files and utilize templateData variables and helpers to access configuration values. While experimenting with Hogan, I managed to retrieve the variables but encountered difficulty in invoking the helpers. ...

Is it possible to show or hide a DIV based on the text content of another DIV using JavaScript in

I am looking for a way to dynamically hide a DIV based on user roles using only the text inside a title tag as a reference. Here is an example of the HTML structure: <title>admin</title> If the user role is admin, then hide the following DI ...

Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: https://i.sstatic.net/bgtPB.png In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly. In Vue 2, I could send an event from ChildA: ...