Sterling Archer
Sterling Archer

Reputation: 22395

Set ng-model value to button click

I have this little snippet of code to set the root.lowWeight and root.highWeight to my controller.

<input type="number" placeholder="Enter Low Range..." class="form-control input-xs">
<input type="number" placeholder="Enter High Range..." class="form-control input-xs">
<button class="btn btn-primary" ng-click="assignWeights()">Select Model</button>

Controller model:

//set the initial root scope to empty object
$scope.root = {};
//define root weight
$scope.root.lowWeight = 0;
$scope.root.highWeight = 0;

I know I could just use ng-model="root.lowWeight" to set the value, but ng-model triggers on element input event.

How can I either:

a) Send the input values in via assignWeights(param1, param2)

b) Change ng-model to trigger input on button click (seems hacky, less preferred solution)

I also know I could use JS/jQuery to trigger the input event and block the input event, but that's a last ditch effort I will 99.9% not do.

Upvotes: 2

Views: 9450

Answers (2)

trees_are_great
trees_are_great

Reputation: 3911

Solution using seperate scope object: plunkr

Html:

Low: <input type="text" name="lowRange" ng-model="inputData.lowWeight">
High: <input type="text" name="highRange" ng-model="inputData.highWeight">

Js:

 $scope.assignWeights = function() {
        $scope.lowWeight = $scope.inputData.lowWeight;
        $scope.highWeight = $scope.inputData.highWeight
  }

Upvotes: 3

developthewebz
developthewebz

Reputation: 1937

In your assignWeights function, you could use a selector to retrieve the values of the inputs and then assign your scope variable values based on that. Just assign a name to each input.

E.g.

<input type="number" placeholder="Enter Low Range..." class="form-control input-xs" name="lowRange">
<input type="number" placeholder="Enter High Range..." class="form-control input-xs" name="highRange">
<button class="btn btn-primary" ng-click="assignWeights()">Select Model</button>

Controller:

$scope.assignWeights = function() {
    $scope.root.lowWeight = document.querySelector('input[name="lowRange"]').value
    $scope.root.highWeight = document.querySelect('input[name="highRange"]').value
}

Plunker: http://plnkr.co/edit/lm8GFA0CD0zWwgAMSLah?p=preview

Upvotes: 0

Related Questions