Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.js - Modify a value from the model by parameter into a function

I have the following view:

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

And this method from the controller:

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

However, the method modify doesn't do anything.

What I want to do is to create a function that can modify an object from the model by parameter. I mean, a function x that recieves an object by parameter, and inside that function, this object (from the model) can be modified.

How can I achieve this?

See this fiddle for reference.

like image 887
lante Avatar asked Jan 21 '14 23:01

lante


2 Answers

It's late, so I could be missing the obvious, however....

Since you're passing a string, it's passed by value instead of reference. So I changed your ng-click to refer to the object on the scope, instead of the value itself.

The modify function then refers to the scope instead of the variable itself.

View

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

Controller

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

    $scope.modify = function (value) {
        $scope[value] = $scope[value] + " and this text";
    };
}
like image 111
Mike Robinson Avatar answered Oct 25 '22 00:10

Mike Robinson


My suggestion would be to pass the name of the variable to the function and modify it as a key/value pair of the scope:

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

and

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

The problem is that Javascript passes simple variables (strings, booleans numbers etc.) by value, while objects and arrays are passed by reference. An alternative would be for your model to be an object with a key text which is modified by your function:

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

and

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

Here is the fiddle

And one for the second approach

like image 1
caffeinated.tech Avatar answered Oct 25 '22 00:10

caffeinated.tech