Angular js 监视带有 ng-repeat 的 Select 标签上的对象数组

Angular js watch on an Array of objects on a Select tag with ng-repeat

本文关键字:Select 标签 对象 数组 ng-repeat js 监视 Angular      更新时间:2023-09-26

我想用ng-repeat观看选择标签并禁用保存按钮。我有这样的设置。

  • 最初,我将有三个带有值的选择框,用户必须从三个框中至少选择一个选择值才能启用Save btn

    • 用户还将具有添加更多选择框的配置。

现在,我如何观看选择框,如果我们有 5 个选择框 - 我们如何观看所有这些并启用/禁用保存按钮,如果没有被选中。

这是一个小提琴链接。与我的情况相似:Js fiddle请帮帮我!!

好吧,您可以将所有选择放在表单中并根据需要进行设置。在按钮中,如果 de form $invalid,则有效禁用 ng 标记。

例:

<ng-form name="selectForm">
  <select class="form-control" ng-model="item.name" name="select" ng-required="true">
    <option>Select a campus</option>
    <option>Campus 1</option>
    <option>Campus 2</option>
    <option>Campus 3</option>        
  </select>
  <button type="submit" ng-disabled="selectForm.$invalid">Save</button>
</ng-form>

您可以在所有ng-select使用同一对象作为模型:

$scope.selectedValues = {};

然后ng-repeat中的每个选择框将不同的对象属性用作模型:

<select class="form-control" ng-model="selectedValues['campus_' + $index]">
    <option>Select a campus</option>
    <option>Campus 1</option>
    <option>Campus 2</option>
    <option>Campus 3</option>        
</select>

要检查是否填充了所有值,您将观察最后一个参数设置为 true 的更改selectedValues

$scope.$watch('selectedValues', function(newValue, oldValue) {
    // Check whether all values in $scope.selectedValues are filled
    var allFilled = true;
    angular.forEach($scope.selectedValues, function(value, key) {
        if (!value) {
            allFilled = false;
        }
    });
    if (allFilled) {
        // enable button
    } else {
        // disable button
    }
}, true);

最后一个参数true是必不可少的,因为它告诉 Angular 比较对象中的所有值。请参阅 https://docs.angularjs.org/api/ng/type/$rootScope.Scope。