控制器ng-模型数据与视图上的ng-模型数据不同

时间:2016-05-27 19:23:46

标签: javascript angularjs controller views

我在使用绑定到控制器中的选择框的数据时遇到问题。当我使用ng-model变量在视图上显示所选数据时,它被绑定到,一切正常。现在,当我尝试在函数中使用控制器中的那些相同值而不是给我选择的值时,它给出了select中的第一个值。

我尝试了所有我知道的解决方法,但无法弄明白......任何帮助都会受到赞赏。我想我错过了一些行为。

使用按钮上的ng-click调用addProduct方法。显示的数据是单击按钮以填充该数据后的结果。

选择框的代码:

<div class="row select-options-container">
    <div class="col">
        <select class="product-options-select" ng-model="sizeOption" ng-options="o as o.size for o in selectOptions" data-ng-change="getIntensityOptions(sizeOption.id)">
        </select>
    </div>

    <div class="col">
        <select class="product-options-select" ng-model="intensityOption" ng-options="o for o in intensityOptions">
        </select>
    </div>
</div>

查看我在下面显示的内容:

<b>CONTROLLER VALUES</b>
<p><b>Size:</b> {{ newSize }}</p>
<p><b>Intensity:</b> {{ newIntensity }}</p>
<p><b>QTY:</b> {{ newQty }}</p>

<b>VIEW VALUES</b>
<p><b>Size:</b> {{ sizeOption.size }}</p>
<p><b>Intensity:</b> {{ intensityOption }}</p>
<p><b>QTY:</b> {{ productQty }}</p>

我在下面显示的控制器代码:

$scope.addProduct = function() {
    $scope.newIntensity = $scope.intensityOption;
    $scope.newSize = $scope.sizeOption.size;
    $scope.newQty = $scope.productQty;
}

This is what I get on the view when I display the data

Select boxes

PS - 所有这些额外的代码都只用于说明问题。

1 个答案:

答案 0 :(得分:0)

从您的代码中看,您似乎没有在正确提交时更新值。

注意:如果我误解了您的目标,请发表评论,我会再次进行审核。

如果您要将表单元素上的ng-model设置为与您尝试将其设置为相同的属性,则此可以工作,但是您不会真正提交它,只会使用存在的绑定功能,例如:

<select class="product-options-select" ng-model="newIntensity" ng-options="o for o in intensityOptions">
</select>

我推荐的解决方案就是这样,允许正确的“提交”操作将数据从页面移动到控制器中:

<强> HTML

<div class="row select-options-container">
    <div class="col">
        <select class="product-options-select" ng-model="formData.sizeOption" ng-options="o as o.size for o in selectOptions" data-ng-change="getIntensityOptions(formData.sizeOption.id)">
        </select>
    </div>

    <div class="col">
        <select class="product-options-select" ng-model="formData.intensityOption" ng-options="o for o in intensityOptions">
        </select>
    </div>
</div>

<!-- assuming you have a submit button of some sort -->
<button ng-click="addProduct(formData)">Add Product</button>

<强> JS

$scope.addProduct = function(formData) {
    $scope.newIntensity = formData.intensityOption;
    $scope.newSize = formData.sizeOption.size;
    $scope.newQty = formData.productQty; // I don't know where this comes from, in the HTML the ng-model should be formData.productQty 
}
相关问题