【问题标题】:Set ng-model value to button click将 ng-model 值设置为按钮单击
【发布时间】:2015-11-23 16:20:26
【问题描述】:

我有这个小sn-p 代码可以将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% 不会做的最后努力。

【问题讨论】:

  • 不确定我是否理解正确,但也许你会寻求这个:docs.angularjs.org/api/ng/directive/ngModelOptions
  • 我不确定你要做什么,你不能只使用ng-model,然后函数将值分配给模型值吗?
  • @Sam 正如我所说,ng-model 绑定到输入事件,所以虽然它可以工作,但它不会绑定到按钮单击。单击按钮时,我需要将其分配给模型
  • 一种解决方案是以不同的名称将其分配给模型 - inputData.lowWeight,然后在按钮单击时使用函数 $scope.root.lowWeight = $scope.inputData.lowWeight

标签: javascript angularjs angular-ngmodel


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    在您的 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
    }
    

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

    【讨论】:

    • 虽然这可能有效,但这不是我需要实现的“角度方式”。不过,谢谢。
    猜你喜欢
    • 2017-05-22
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多