Kyle V.
Kyle V.

Reputation: 4792

Pass Model to Controller to Change in Controller

Here is my situation, I have this HTML:

<input type="text" ng-model="inputModel" />
<div class="button-container">
    <button type="button" ng-click="setValue(inputModel)"></button>
</div>
<input type="text" ng-model="inputModelTwo" />
<div class="button-container">
    <button type="button" ng-click="setValue(inputModelTwo)"></button>
</div>

And my view controller:

$scope.setValue = function (valueToSet) {
    valueToSet = "Some value.";
};

I need to be able to "connect" the input fields and their buttons and I'm doing this by having the respective button pass the respective input field's model to the controller to be modified. The problem is that when I click the button the function fires off and valueToSet is changed but the change isn't reflected back in the view! What am I missing?

Upvotes: 0

Views: 35

Answers (1)

Caspar Harmer
Caspar Harmer

Reputation: 8117

If you are trying to dynamically pass in your models as a function parameter, you'll need to access a PROPERTY on the models by using dot notation.

Try defining the models in the controller like so:

$scope.inputModel = {};
$scope.inputModelTwo = {};

$scope.inputModel.text = 'hey';
$scope.inputModelTwo.text = 'ho';

Then pass in the entire model to the function as you were already doing.

Inside the function, alter the property that you desire (in this case 'text'), like so:

$scope.setValue = function (valueToSet) {
    console.log(valueToSet);
   valueToSet.text = "Some value.";
};

JSFiddle

Upvotes: 1

Related Questions