首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 ><select ng-options="...“/>的问题

<select ng-options="...“/>的问题
EN

Stack Overflow用户
提问于 2015-05-13 20:30:44
回答 1查看 75关注 0票数 3

我试着用AngularJS实现一个简单的特性,如下所示。在项目列表中,当用户单击某个项目并单击删除按钮时,该项目将被删除。

html:

代码语言:javascript
复制
<div ng-app="app" ng-controller="MainController">
    <div>
      <select ng-options="item.name for item in items" ng-model="currentItem" size="5" style="width: 200px"></select>
    </div>
    <button ng-click="removeItem()">Remove</button>
  </div>

脚本如下:

代码语言:javascript
复制
angular.module('app', [])
  .controller('MainController', function($scope) {
    $scope.items = [{
      name: 'item1'
    }, {
      name: 'item2'
    }, {
      name: 'item3'
    }];

    $scope.currentItem = $scope.items[0];

    $scope.removeItem = function() {
      var index = $scope.items.indexOf($scope.currentItem);
      $scope.items.splice(index, 1);
    };

  });

问题是,当我试图删除一个项目(即item2)时,列表总是在第一个位置显示一个空项目。当我点击'item1‘或'item3’时,空的项目消失了。

我知道这是由html中的ng-model="currentItem"引起的。currentItem指向要删除的项,currentItem指向null。所以我修改了函数removeItem,如下所示来解决这个问题。

代码语言:javascript
复制
$scope.removeItem = function() {
      var index = $scope.items.indexOf($scope.currentItem);
      $scope.items.splice(index, 1);

      /* PART 1 begin */
      if ($scope.items.length === 0) {
        $scope.currentItem = null;
      } else {
        if (index >= 0 && index <= $scope.items.length - 1) {
          $scope.currentItem = $scope.items[index];
        } else {
          $scope.currentItem = $scope.items[$scope.items.length - 1];
        }
      }
      /* PART 1 end */
    };

我想知道在AngularJS中是否有任何简单的方法(如指令)来自动完成第1部分中的操作。

EN

回答 1

Stack Overflow用户

发布于 2015-05-13 20:46:47

有一种简单方法可以防止这种情况,只需包含

代码语言:javascript
复制
 <option value="" ng-show="false"></option>

在如下所示select like中

代码语言:javascript
复制
<select ng-options="item as item.name for item in items" ng-model="currentItem" size="5" style="width: 200px">
   <option value="" ng-show="false"></option>
</select>

更新1

我已经解决了不突出显示最后一项的问题,请看一下工作演示

代码语言:javascript
复制
$scope.removeItem = function () {
    var index = $scope.items.indexOf($scope.currentItem);
    $scope.items.splice(index, 1);
    index === $scope.items.length ? $scope.currentItem = $scope.items[index - 1] : $scope.currentItem = $scope.items[index];
};
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30214831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档