Angular.js - 将带有特殊字符和数字的字符串转换为数组,并使用ng-repeat显示

时间:2016-03-13 18:20:33

标签: javascript arrays angularjs angularjs-ng-repeat

我是angular.js的新手,我遇到了将字符串转换为数组并使用ng-repeat显示的问题,到目前为止我从a stackoverflow question获得了这个自定义过滤器,代码是:

JS:

var app = angular.module('globalModule', [])

    app.controller("SampleController", function($scope){

        $scope.data = "123abc123";
    }); 


    app.filter("spaceBreak", 
        function () {
            return function ( value ) {
                  if( !value.length ) return;
                      return value.split("");   
            }
        });

HTML:

 <body ng-controller="SampleController">
     <h4 id="id_{{$index}}" ng-repeat="value in data | spaceBreak"><span ng-bind="value"></span></h4>
</body>

我的问题是,如果单独使用字母表(abc)或数字(123),它会正确转换和显示,如果组合(abc123)或(123abc)仍然很好,但如果数据是数字+字母+数字(123abc123)它在ng-repeat中不再显示。我真的迷路了,真的需要帮助。希望有人可以给我一个答案。

1 个答案:

答案 0 :(得分:2)

我认为您正在寻找的是track by $index功能。您编写错误代码,因为您的$scope.data中有重复项。该过滤器并不能为您做任何事情,因此您可以通过ng-repeat字符串$scope.data

&#13;
&#13;
var app = angular.module('globalModule', [])

app.controller("SampleController", function($scope){

  $scope.data = "123abc123"; 
})
&#13;
<!DOCTYPE html>
<html ng-app="globalModule">

  <head>
    <script data-require="angular.js@1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="SampleController">
    <h4 id="id_{{$index}}" ng-repeat="value in data track by $index"><span ng-bind="value"></span></h4>
  </body>

</html>
&#13;
&#13;
&#13;