Angular.js - Update a model value through a function using a parameter

I am currently faced with the following scenarios:

<input ng-model="something" />
<button ng-click="modify(something)">Modify</button>

Within the controller, there is this method:

$scope.modify = function (value) {
    value = value + " and some additional text";
};

Despite having the modify method in place, it seems to be ineffective.

My objective revolves around creating a function capable of altering an object from the model based on parameters provided. For instance, a function x that takes an object as input parameter, allowing modifications to said object within the function itself.

What steps should I take to accomplish this goal?

For further details, refer to this sample fiddle.

Answer №1

It's getting late, so I might be overlooking the obvious, but...

When passing a string, it is passed by value rather than reference. That's why I updated your ng-click to point to the object on the scope, instead of the actual value.

The modify function now references the scope instead of the variable itself.

Check out the code snippet below:

<div ng-app>
    <div ng-controller="SomeCtrl">
        <input ng-model="something" />
        <button ng-click="modify('something')">Modify</button>
    </div>
</div>

Here's the controller code:

function SomeCtrl($scope) {
    $scope.something = "test";

    $scope.modify = function (value) {
        $scope[value] = $scope[value] + " and this text";
    };
}

Answer №2

To improve your code, I recommend passing the variable name to the function and updating it as a key/value pair in the scope:

<button ng-click="update('example')">Update</button>

Next, modify your function like this:

$scope.update = function(value){
    $scope[value] = $scope[value] + " with this new text";
};

The issue lies in how Javascript handles variables - simple ones are passed by value, while objects and arrays are passed by reference. Consider using an object model with a 'text' key that gets updated by the function:

<button ng-click="update(data)">Update</button>

and update your function accordingly:

$scope.data = {text: "data"};
$scope.update = function(value){
    value.text = value.text + " with this new text";
};

Check out this JSFiddle link for the first approach.

Alternatively, you can also look at this second approach on JSFiddle.

Answer №3

Manage the variables internally instead.

To simplify your function call, eliminate the variable:

<input ng-model="something" />
<button ng-click="update()">Update</button>

Within your controller, reference something as a $scope variable:

$scope.update = function () {
    $scope.something = $scope.something + " along with this extra text";
};

Answer №4

If you need assistance, you have the option to modify a model value through a function.

var app = angular.module('angularjs-starter', []);

app.controller('addRemoveVehicleCntrlr', function($scope) {

  $scope.vehicles = [{
    id: 'vehicle1'
  }];
  var allVins = [];
  $scope.addNewVehicle = function() {
    var newItemNo = $scope.vehicles.length + 1;
    $scope.vehicles.push({
      'id': 'vehicle' + newItemNo
    });
    // console.log($scope.vehicles);
  };
  $scope.getdetail = function(name, index, value) {
    console.log(name + index);
    allVins.splice(index, 1, {
      "vin": name,
      "trim": value
    });
    console.log(allVins);
    $scope.myval = "dd";
  }
  $scope.changeDetails = function(index, value) {
    // allVins.splice(index, 1, {"trim":value});
    allVins[index].trim = value
    console.log(allVins);
  }
  $scope.removeVehicle = function(index) {
    $scope.vehicles.splice(index, 1);
    allVins.splice(index, 1);
    console.log(allVins)
  };

});
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.js"></script>
<div ng-app="angularjs-starter" ng-controller="addRemoveVehicleCntrlr">
  <div style="background:#cecece; padding:10px;">
    <div style="background:#EBEBEB; padding:10px; margin-bottom:3px" data-ng-repeat="vehicle in vehicles">
      <input type="text" ng-model="vehicle.name" name="" placeholder="Enter mobile number">
      <input type="button" value="Review" ng-click="getdetail(vehicle.name, $index, vehicle.value)" />
      <div id="myVal">{{myval}}</div>
      <a class="remove" ng-show="vehicles.length > 1" ng-click="removeVehicle($index)">Remove vehicle</a>
    </div>
  </div>
  <button class="addfields" ng-click="addNewVehicle()">Add Vehicle</button>
</div>

View on Plunker

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

JavaScript post method for JSON data: no input or output values

I am currently developing a page that extracts data from an HTML table consisting of two columns and an index of a form, and then converts it into a JSON string. The intention is to pass this data into PHP for further processing, perform calculations on th ...

Access the checkboxes that were previously selected and store them for future use when the page is

I am working on an HTML code where checkboxes are automatically checked and upon clicking a button, the values of checkboxes are passed through a function. Additionally, when a user checks a checkbox, the corresponding children checkboxes are also checked. ...

Successfully transferred file to new location within the same directory without encountering any issues

After converting my uploaded file from base64 to "xxx" file type, I am sending a JSON query to my PHP file. Here's how the request is being made: $http.post( preUrl + 'assets/new.php', data ); The response shows no errors and every ...

Tips for resolving conflicts with jQuery on an ASP.NET webpage

On this page, I am using references and scripts for a date time picker and color box. However, only one of them works at a time - commenting out one script allows the other to work. I have tried using jQuery noconflict, but it did not resolve the issue. H ...

What is the best way to save a parsed JSON value to a variable in Express?

I am currently utilizing the body-parser module to parse incoming JSON objects within a POST request. My goal is to extract and store a specific value from the JSON data into a variable for later database insertion. Below is a fragment of the code: var h ...

Unable to locate the data-block for angular-blocks

I am having an issue with using 'angular-blocks' as I keep receiving a warning. In my template (/fc-layout.html), the code looks like this: <script type="text/ng-template" id="/fc-layout.html"> <div data-block="fc"> < ...

Pass a link by pressing Enter

Although the title may seem odd, I'll explain what I'm attempting to accomplish. I have a login form with two input fields, a checkbox, and a submit button. You can view a screenshot of it here: https://i.sstatic.net/nE1FY.png The terms of use a ...

The Signature Pad loses its focus

My HTML code is using JavaScript with Bootstrap and the Signature Pad. The issue I am facing is related to the Bootstrap Collapse feature. When I set the first panel as default, the Signature Pad does not allow me to sign. However, if I set the third panel ...

What is the best way to showcase the following values using Vue.js?

{"status":true,"data":[{"ref_id":"22","agent_id":"68","p_id":"84","description":"i am interested"},{"ref_id":"24","agent_id":"68","p_id":"84","description":"For more information about Bootstrap and Bootstrap Glyphicons, visit our Bootstrap Tutorial.For mor ...

The issue arises when attempting to utilize ExpressJS middleware in conjunction with NextJS Link feature

Incorporating Next with Express routes, I have set up a scenario where /a should only be accessible to authorized individuals, while /b is open to the public. ... other imports... const app = next({ isDev }) const handle = app.getRequestHandler() async f ...

Guide to downloading a file from a byte base64 in Vue.js

I am dealing with a byte base64 string let data = 'UEsDBBQABgAIAAAAIQBi7...' If I want to download the file from this byte base64 in vue js, what should I do? Any suggestions or solutions would be greatly appreciated :') ...

"Enhancing Hangman by updating the object-oriented array of values

I'm currently working on developing a hangman game using PHP and JS, but I've encountered some issues. In my project, there are two arrays involved - the answer array containing the correct letters and the user answer array storing the user' ...

The system encountered an issue while trying to access the 'bannable' property, as it was undefined

message.mentions.members.forEach(men => { let member = message.mentions.members.get(men) if (!member.bannable) return message.reply(not_bannable) const reason = args.slice(1).join(" "); member.ban({reason: reason ...

Asynchronous Node operations with Promise.all

When working on a basic JS program, I encountered the need for asyncOperation2 and asyncOperation3 to run in sequence with asyncOperation1. The specific order of execution required is either 1,2,3 or 2,3,1. Additionally, after completing these operations, ...

Which core modules of Node Js serve as the foundation for Express Js?

Which core modules of Node.Js are utilized in the construction of the Express Js Framework? Besides the 'http' and 'fs' modules, what other modules does Express Js integrate? ...

Choose an option from the drop-down menu

I am currently working on a drop-down menu that displays country codes and their respective full names. Here is an example: <script> var app = angular.module('myApp', []); app.controller('myCtrl', func ...

The AngularJS HTTP interceptor is a crucial component for handling

Is there a way to use an interceptor in AngularJS to log "finished AJAX request" when any request is completed? I've been exploring interceptors and currently have the following setup, but it triggers at the beginning of the request rather than the e ...

Several jQuery ajax requests seem to be failing due to errors in previous calls

I am experiencing an issue with my website's login form that utilizes ajax to send the login information to php. After successfully logging in, users have the ability to log out and then return to the login page again. However, I am facing a problem w ...

What are the steps for configuring a dynamic variable?

One issue I encountered was setting up a variable in vue that updates when the screen orientation changes. Despite adding this variable to the data object, it did not become reactive as expected. This is my initial data function for the component: data() ...

Tips for compressing an image in a React application with the help of react-dropzone

I have integrated the react dropzone package into my Next JS app and I am looking to add automatic image compression feature. After receiving the images, I converted the blob/preview into a file reader. Then, I utilized the compressorjs package for compre ...