从数组中删除一个值并将它们移动到另一个数组

Removing a value from an array and moving them to another Array

我有一个来自 $scope.role 的下拉值,我可以从那里 select 并从该下拉列表中删除相应的值并将值移动到 $scope.multiRoles 数组。我也将其显示为标签。可以在 AddRole()

中找到

现在,当我单击标签中的关闭按钮时,我正在调用 removeRoles() ,我正在拼接我正在 selected 的数组。但我需要拼接它们并将它们移回 $scope.role。直到删除值它工作正常,但我也无法将它移回 $scope.role。我需要至少保留一个标签,我不能全部删除。

HTML:

<div class="row newRow">
  <div class="form-group fields col-sm-2 col-xs-4">
    <label>ROLE *</label>
    <select name="role" class="form-control1 drop2" required ng-model="model.role" placeholder="select">
      <option value='' disabled selected>Select</option>
      <option ng-repeat="item in role track by $index" value="{{item}}">{{item}}</option>
    </select>
  </div>
  <div class="form-group  col-sm-2 col-xs-4">
    <button ng-click="AddRole($index)">Click to Add your Role</button>
  </div>
</div>
<div ng-if="rolesAdded" class="col-sm-12 col-xs-12">
  <span class="tag label tagStyle newStyling" alue="data" ng-repeat="data in multiRoles track by $index">
    <span>{{data}}</span>
  <a><i ng-click="removeSelection()"class="remove glyphicon glyphicon-remove-sign "></i></a>
  </span>
</div>

JS:

$scope.AddRole = function(index) {
  debugger;
  if ($scope.model.role !== undefined) {
    $scope.multiRoles.push($scope.model.role);
    var index = $scope.role.indexOf($scope.model.role); //just find the right index which is the selected option in dropdown.
    $scope.role.splice(index, 1);
    console.log($scope.role);
    $scope.model.role = $scope.role[0];
  }
  $scope.rolesAdded = true;
};

$scope.removeRoles = function(index) {
  debugger;
  if ($scope.multiRoles !== null) {
    $scope.multiRoles.splice(index, 1);

  }
};

在您的 html 中将 data 导入您的 removeRoles(data) 函数:

<button ng-click="removeRoles(data)">
  <i class="remove glyphicon glyphicon-remove-sign"></i>
</button>

在你的控制器中:

$scope.removeSelection = function(data) {
  $scope.multiRoles.splice($scope.multiRoles.indexOf(data), 1);
  $scope.role.push(data);
  $scope.rolesAdded = $scope.multiRoles.length === 0 ? false : true;
};

代码here。希望这有帮助。