当使用带有过滤器的`track by $ index`时,我收到错误。怎么解决这个?

时间:2016-02-22 12:55:17

标签: javascript jquery angularjs

我有一个错误的数组值作为字符串。它有重复的值。我想从数组字符串中删除不需要的空格和数字。所以我使用过滤器清洁所有。

问题是,当我单独使用过滤器时,如果我删除了duplicates我收到错误,我的过滤器无效。

如何处理这种情况?

这是我的代码:

var myApp = angular.module('myApp',[]);

arr=[
  "1. Completion of Site mobilization \n2. Erection of Tower cranes 2, 4 & 5\n3. Facade dismantling  (Grey ACP between Gates 19, 23 & 24;  Steel Louvers between Gates 2 & 3)                                                                       \n4. Excavation for Foundation (AHU Corridor,  Foundation Area 1, 2  &3, External Buildings)\n5. Civil Works on East Expansion for foundation  (F50, F52, F55, F57, F94)\n6. West Stand Roof catwalks dismantling completed 100 %\n7. Assembly/Erection of temporary towers for Lighting Arch \n    dismantling\n8. Score Board dismantling\n9. Completion of Site mobilization 10. Erection of Tower cranes 2, 4 & 5\n11. Facade dismantling  (Grey ACP between Gates 19, 23 & 24;  Steel Louvers between Gates 2 & 3)                                                                       \n12. Excavation for Foundation (AHU Corridor,  Foundation Area 1, 2  &3, External Buildings)\n13. Civil Works on East Expansion for foundation  (F50, F52, F55, F57, F94)14. West Stand Roof catwalks dismantling completed 100 %\n15. Assembly/Erection of temporary towers for Lighting Arch \n    dismantling\n16. Score Board dismantling",
  "",
  ""
]


myApp.controller('main', function($scope){

    $scope.arrays = arr;

});

angular.module("myApp")
.filter("string2array", 

    function () {

        return function ( value ) {

            if(!value) return;

            return value.filter(Boolean).join('\n').replace(/^\d+\.\s+/gm, '').split('\n');

        }

});

这是我的js尝试:Js Demo

这里是angularjs整合,这对我来说是个问题

angualrjs demo

3 个答案:

答案 0 :(得分:1)

过滤器已应用于arrays,因此您只需要执行..

<li ng-repeat="array in arrays | string2array track by $index">

fiddle

答案 1 :(得分:1)

为什么要使用过滤器?如果我理解正确,你需要将你的字符串拆分成一个数组然后处理它。所以,在你的控制器中尝试一下,摆脱你的过滤器:

$scope.arrays = arr.filter(Boolean).join('\n').replace(/^\d+\.\s+/gm, '').split('\n');

答案 2 :(得分:1)

您已将过滤器放在错误的位置,并尝试过滤$index,这是一个不是数组的数字。

尝试

 <li ng-repeat="array in arrays | string2array track by $index ">{{array }}</li>

读取有关查询语法顺序的ng-repeat`文档