将 ng-model 值设置为按钮单击

Set ng-model value to button click

我有一小段代码可以将 root.lowWeightroot.highWeight 设置到我的控制器。

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

控制器型号:

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

我知道我可以只使用 ng-model="root.lowWeight" 来设置值,但是 ng-model 在元素 input 事件上触发。

我怎样才能:

a) 通过 assignWeights(param1, param2)

发送输入值

b) 更改 ng-model 以在单击按钮时触发输入(看起来很老套,不太受欢迎的解决方案)

我也知道我可以使用 JS/jQuery 来触发输入事件并阻止输入事件,但这是我 99.9% 不会做的最后一搏。

在您的 assignWeights 函数中,您可以使用选择器检索输入的值,然后根据它分配您的范围变量值。只需为每个输入分配一个名称。

例如

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

控制器:

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

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

使用单独范围对象的解决方案: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
  }