使用ng选项添加额外/默认选项

Adding extra/default option using ng-options

本文关键字:选项 默认 添加 ng 使用      更新时间:2023-09-26

我正在构建一个角度形式的标签管理器,它使用两个下拉菜单(在这个演示中是一个食物类别和一个特定项目)。当用户选择一个食物类别时,项目下拉列表应该出现,当下拉列表中选择了一个值时,我希望以":"的格式将一个字符串添加到我的标签列表中。以下是代码:

app.js

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
  $scope.tags = [];
  $scope.userCategory;
  $scope.userFood;
  $scope.primaryFoods = [
    {
        'id': 1,
        'parent_id': null,
        'name': 'Pizza'
    },
    {
        'id': 4,
        'parent_id': null,
        'name': 'Burgers'
    },
    {
        'id': 7,
        'parent_id': null,
        'name': 'Pasta'
    },
  ];
  $scope.secondaryFoods = [
    {
        'id': 2,
        'parent_id': 1,
        'name': 'Cheese Pizza'
    },
    {
        'id': 3,
        'parent_id': 1,
        'name': 'Combo Pizza'
    },
    {
        'id': 5,
        'parent_id': 4,
        'name': 'Cheese Burgers'
    },
    {
        'id': 6,
        'parent_id': 4,
        'name': 'Hamburgers'
    },
  ];
});
app.directive('doubleTagManager', function() {
  return {
    restrict: 'E',
    scope: {tags: '=', primary: '=', secondary: '=', userPrimary: '=', userSecondary: '='},
    templateUrl: 'double-tag-manager.html',
    link: function ($scope, $element) {
      var input = angular.element($element.find('select')[1]);
      // This adds the new tag to the tags array in '<Primary>: <Secondary>' format
      $scope.add = function() {
        var new_value = input[0].value;
        if ($scope.tags.indexOf(new_value) < 0) {
          $scope.tags.push($scope.userPrimary.name + ': ' + $scope.userSecondary.name);
        }
      };
      // This is the ng-click handler to remove an item
      $scope.remove = function (idx) {
          $scope.tags.splice(idx, 1);
      };
      input.bind( 'change', function (event) {
        $scope.$apply($scope.add);
      });
    }
  };
});

双标签管理器.html

<div class="row">
  <div class="col-md-6">
    <select name="uFoodsPrimary" id="foodPrimary" class="form-control"
            ng-model="userPrimary"
            ng-options="item.name for item in primary track by item.name" required>
      <option value="">Select a Food category!</option>
    </select>
  </div>
  <div class="col-md-6" ng-show="userPrimary">
    <select name="uFoodsSecondary" id="foodSecondary" class="form-control"
            ng-model="userSecondary"
            ng-options="item.name for item in (secondary | filter: {parent_id: userPrimary.id})
            track by item.name"
            required>
      <option value="">Select a Food sub-category!</option>
    </select>
  </div>
</div>
<div class="tags">
  <a ng-repeat="(idx, tag) in tags" class="tag" ng-click="remove(idx)">{{tag}}</a>
</div>

我想添加的是选择"所有食物"的功能,这样用户就不需要单独选择所有食物,但我似乎不知道如何使用ng选项添加额外的字段。

Fiddle

奖金:如果选择了一个没有子项的类别,我希望默认情况下将其添加到标签列表中。

Erik,以下是修改后的代码,以实现您的全选功能。此外,您还可以对其进行更多的增强,以实现奖金用例。

与其花太多精力以这种方式实现标记,我建议使用现有的angularui-select2组件。它还有很多其他选择。它会让你的生活更轻松。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.tags = [];
  $scope.sub_cat_show = false;
  $scope.all_sub_cat_show = false;
  $scope.userCategory;
  $scope.userFood;
  $scope.primaryFoods = [{
    'id': 0,
    'parent_id': null,
    'name': 'All Foods'
  }, {
    'id': 1,
    'parent_id': null,
    'name': 'Pizza'
  }, {
    'id': 4,
    'parent_id': null,
    'name': 'Burgers'
  }, {
    'id': 7,
    'parent_id': null,
    'name': 'Pasta'
  }];
  $scope.secondaryFoods = [
  {
    'id': 2,
    'parent_id': 1,
    'name': 'Cheese Pizza'
  }, {
    'id': 3,
    'parent_id': 1,
    'name': 'Combo Pizza'
  }, {
    'id': 5,
    'parent_id': 4,
    'name': 'Cheese Burgers'
  }, {
    'id': 6,
    'parent_id': 4,
    'name': 'Hamburgers'
  }, ];
});
app.directive('doubleTagManager', function() {
  return {
    restrict: 'E',
    scope: {
      tags: '=',
      primary: '=',
      secondary: '=',
      userPrimary: '=',
      userSecondary: '=',
      sub_cat_show: '=',
      'all_sub_cat_show': '='
    },
    template: "<div class='row'><div class='col-md-6'><select ng-change='primaryChange()' name='uFoodsPrimary' id='foodPrimary' class='form-control' ng-model='userPrimary' ng-options='item.name for item in primary track by item.name' required> <option value=''>Select a Food category!</option></select></div><div ng-show='sub_cat_show' class='col-md-6'><select ng-show='all_sub_cat_show' ng-change='secondaryChange()' name='uFoodsSecondary' id='foodSecondary' class='form-control' ng-model='userSecondary'" +
      //options code
      "ng-options='item.name for item in (secondary | filter: {parent_id: userPrimary.id}) track by item.name' required>" +
      //end options code
      "<option value=''>Select a Food sub-category!</option></select> <select ng-show='!all_sub_cat_show'><option value=''>Food all sub-category</option></select> </div></div><div><a ng-repeat='(idx, tag) in tags' class='tag' ng-click='remove(idx)'>{{tag}}</a></div>",
    link: function($scope, $element) {
      var primarySel = angular.element($element.find('select')[0]);
      var secondarySel = angular.element($element.find('select')[1]);
      // This adds the new tag to the tags array in '<Primary>: <Secondary>' format
      $scope.primaryChange = function() {
        $scope.tags = []; // reset
        $scope.sub_cat_show = primarySel[0].value?true:false;
        if (primarySel[0].value == 'All Foods')
        {
          $scope.all_sub_cat_show = false;
          angular.forEach($scope.primary, function(primary, index) {
            angular.forEach($scope.secondary, function(secondary, index) {
              if(secondary.parent_id==primary.id)
                  $scope.tags.push(primary.name + ': ' + secondary.name);
            });
          });
        }
        
        else
        {
          $scope.all_sub_cat_show = true;
        }
      }
      
      $scope.secondaryChange = function() {
          var new_value = secondarySel[0].value;
          if ($scope.tags.indexOf(new_value) < 0) {
            $scope.tags.push(primarySel[0].value + ': ' + new_value);
          }
        };
      // This is the ng-click handler to remove an item
      $scope.remove = function(idx) {
        $scope.tags.splice(idx, 1);
      };
    }
  };
});
<script src="https://code.angularjs.org/1.4.3/angular-animate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<!DOCTYPE html>
<html >
<head>
  <meta charset="utf-8" />
  <title>AngularJS Demo</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
</head>
<body>
  <div ng-app="myApp" ng-controller="myCtrl">
    <double-tag-manager tags="tags" primary="primaryFoods" secondary="secondaryFoods" user-primary="userCategory" user-secondary="userFood">
    </double-tag-manager>
  </div>
</body>
</html>

在深入研究堆栈溢出之后,最好的(也许也是唯一的)解决方案是链接另一个过滤器,该过滤器将克隆已筛选的数组并取消转移另一个选项。

新过滤器:

app.filter('addAll', function () {
  return function(input) {
    // clone the array, or you'll end up with a new "None" option added to your "values"
    // array on every digest cycle.
    var newArray = input.slice(0);
    newArray.unshift({name: "All Foods"});
    return newArray;
  };
});

更新的ng选项标签:

ng-options="item.name for item in (secondary | filter: {parent_id: userPrimary.id} | addAll)
            track by item.name"

SO后

更新的Fiddle