如何在按钮上移动对象内部按钮单击?

Bra*_*n07 1 angularjs ng-repeat

我在ng-repeat中有一个很棒的项目列表,每个项目都有一个向上和向下按钮.我只想要向上按钮将列表项向上移动一个位置,向下按钮应将其向下移动一个位置.问题是我收到一条错误,上面写着"无法读取未定义的属性'NaN'." 似乎"位置"在第二行未定义.我该怎么做才能解决这个问题?

继承人我正在使用的javascript(感谢Rishul Matta):

$scope.moveUp = function(ind, position) {
       $scope.temp = $scope.list[position - 1];
       $scope.list[position - 1] = $scope.list[position];
       $scope.list[position = temp];
  };
Run Code Online (Sandbox Code Playgroud)

这是我的HTML:

<ul>
  <li class="steps" ng-repeat="step in selectedWorkflow.Steps track by $index" ng-class="{'words' : step.Id != selectedStep.Id, 'selectedWords' : step.Id == selectedStep.Id}" ng-model="selectedWorkflow.Step" ng-click="selectStep(step, $index); toggleShow('showSubStep'); toggleShow('showEditBtn')">
      {{step.Name}}
      <input class="orderUpBtn" type="button" ng-click="moveUp($index, step)" style="z-index:50" value="U" />
      <input class="orderDownBtn" type="button" style="z-index:50" value="D" /> 
  </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

谢谢!

小智 10

感谢您发布此问题(+1)和答案jtrussell(+1).我想与其他人分享我认为更可重用/模块化的答案(受odetocode.com帖子的启发).

对于HTML,jtrussell的代码是完美的,因为他修复/简化了一切.为了获得更好的用户体验,我刚为第一个/最后一个元素添加了ng-disabled.

HTML:

<ul ng-controller="DemoCtrl as demo">
    <li ng-repeat="item in demo.list">
        {{item}}
        <button class="move-up"
            ng-click="listItemUp($index)"
            ng-disabled="$first">
                Move Up
        </button>
        <button class="move-down"
            ng-click="listItemDown($index)"
            ng-disabled="$last">
            Move Down
    </button>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

对于JS,请注意我认为更可重用的moveItem()函数.您也可以将此功能用于其他拖放交换功能.

Controller中的JS(在Angular 1.3.15上测试):

// Move list items up or down or swap
$scope.moveItem = function (origin, destination) {
    var temp = $scope.list[destination];
    $scope.list[destination] = $scope.list[origin];
    $scope.list[origin] = temp;
};

// Move list item Up
$scope.listItemUp = function (itemIndex) {
    $scope.moveItem(itemIndex, itemIndex - 1);
};

// Move list item Down
$scope.listItemDown = function (itemIndex) {
    $scope.moveItem(itemIndex, itemIndex + 1);
};
Run Code Online (Sandbox Code Playgroud)

我希望对那里的人有所帮助.谢谢SO社区!