Search code examples
javascriptangularjsangular-ngmodel

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.


Solution

  • 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
      }