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.
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";
};
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With