从数组中删除一个值并将其移动到另一个数组 [英] Removing a value from an array and moving them to another Array

查看:139
本文介绍了从数组中删除一个值并将其移动到另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从$scope.role中有一个下拉列表值,我可以从该下拉列表中选择并删除相应的值,然后将这些值移动到$scope.multiRoles数组中.我也将其显示为标签.可以在AddRole()

I have a dropdown values from $scope.role from there I am able to select and remove the respective value from that dropdown and moving the values to $scope.multiRoles array . Which I am also displaying as tags .Which can be find in AddRole()

现在,当我单击标记中的关闭按钮时,我将调用removeRoles(),在这里将选定的数组拼接起来.但是我需要将它们拼接起来并将它们移回$scope.role.直到删除值,它都可以正常工作,但我也无法将其移回$scope.role.我需要至少保留一个标签,我无法删除所有标签.

Now when I click close button in the tag, I am calling removeRoles() , where I am splicing the array which I am selected. But I need to splice them and move them back to $scope.role. Till removing value it works fine , but I am unable to move it back to $scope.role as well. I need atleast one tag should be remained, I can not delete all of them.

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)函数中:

In your html import data to your removeRoles(data) function:

<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;
};

代码此处.希望这会有所帮助.

Code here. Hope this helps.

这篇关于从数组中删除一个值并将其移动到另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆