删除后ng-repeat中的$ index未更新

时间:2015-05-06 12:23:12

标签: angularjs dynamic indexing

情况

image上你可以看到我想要的东西。单击ng-repeat时,使用+step动态添加一行输入字段。 x删除了一个步骤,up and down arrows向上或向下移动了第一步 我希望当一个步骤不能更高时禁用向上箭头,而当它不能降低时禁用向下箭头。到目前为止,当我只添加步骤(并没有删除)时,它完美无缺。 但是,当我删除一个步骤时,$indexng-disabled中不会更新,尽管我打印时它似乎已更新。

问题

这是我删除第一步后得到的结果: image
如您所见,向下数组被禁用。虽然打印索引为0,但ng-disabled中的索引仍必须为1.

HTML:

<div class="col-sm-2 nopadding">
    <div class="btn-group btn-lg" role="group">
        <!--move step up-->
        <button type="button" class="btn iconbutton  " ng-click="" ng-disabled="{{$index}}==0"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true"></span> 
        </button>
        <!--move step down-->
        <button type="button" class="btn iconbutton " ng-click="" ng-disabled="{{$index}}==normal.length-1"><span class="glyphicon glyphicon-arrow-down" aria-hidden="true"></span> 
        </button>
        <!--remove step-->
        <button type="button" class="btn iconbutton " ng-click="removeStep(step,'normal',0)"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> 
        </button>
    </div>
    <p>index={{$index}}, length= {{normal.length}}</p>
</div>

删除控制器中的功能:

$scope.removeStep = function (item,flow,index) {
   if(angular.equals(flow,'normal')){
        var i = $scope.normal.indexOf(item);
        $scope.normal.splice(i, 1); 

   }
   if(angular.equals(flow,'alternative')){
        var i = $scope.alternative[index].behavior.indexOf(item);
        $scope.alternative[index].behavior.splice(i, 1); 


   }
   if(angular.equals(flow,'exceptional')){
        var i = $scope.exceptional[index].behavior.indexOf(item);
        $scope.exceptional[index].behavior.splice(i, 1); 
   }

};

更新:找到了解决方法

它不像使用$ index那样干净,但是我在我的控制器中写了一个函数,给定该项,它返回数组中该项的位置。这适用于所有情况

2 个答案:

答案 0 :(得分:2)

用户跟踪$ index

    webClient.setJavaScriptTimeout(JAVASCRIPT_TIMOUT);
    webClient.getOptions().setTimeout(WEB_TIMEOUT);
    webClient.getOptions().setCssEnabled(false);
    webClient.getOptions().setThrowExceptionOnScriptError(false); 
    webClient.getOptions().setPopupBlockerEnabled(true);
    webClient.setRefreshHandler(new WaitingRefreshHandler(REFRESH_HANDLER_WAIT_LIMIT)); 

当您从数组中删除元素时,数组元素将被重新编入索引,而angular将删除关联的dom元素。但它不会使用新的索引数组重新呈现视图。这就是为什么从数组中删除元素后$ index的值不会改变的原因。如果你使用$ index跟踪,那么angular也会跟踪$ index并相应地更新它的值。

答案 1 :(得分:0)

根据https://docs.angularjs.org/api/ng/directive/ngRepeat中的ng-repeat文档,您可以使用ng-repeat范围特定的$ first和$ last范围变量识别第一次和最后一次ng-repeat迭代,而不是使用ng-disabled =&# 34; {{$索引}} == 0&#34;对于向上箭头,您可以使用ng-disabled =&#34; {{$ first}}&#34;。

这将是我第一次尝试没有完整资源来测试它的问题。

相关问题