【问题标题】:Angular.js - Convert string with special characters and numbers into Array and display with ng-repeatAngular.js - 将带有特殊字符和数字的字符串转换为数组并使用 ng-repeat 显示
【发布时间】:2016-03-14 02:50:56
【问题描述】:

我是 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 中显示。我真的迷路了,真的需要帮助。希望有人能给我答案。

【问题讨论】:

  • 有点困惑...所以您希望将字符串123abc123 拆分为一个数组并在您的ng-repeat 中显示为123abc123
  • 不,我想单独拆分它,例如 1,2,3,a,b,c,1,2,3 拆分 abc123 和 123abc 没有问题,但使用 123abc123 它不显示。我不知道为什么,字符也一样,比如!abc!它没有显示在 ng-repeat 中。

标签: javascript arrays angularjs angularjs-ng-repeat


【解决方案1】:

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

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

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

  $scope.data = "123abc123"; 
})
<!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>

【讨论】:

  • 不错的答案,我不知道ng-repeat 也会遍历字符串。一个问题,lodash 这里是干什么用的?
  • 抱歉,不是。我自动驾驶将它添加到每个sn-p,哈哈。将删除,谢谢。
  • 另外,对于 OP,这里是 official Angular explanation 说明为什么 ng-repeat 中的重复是一个问题。
  • 哦,你救了我,伙计!非常感谢!通过 $index 添加轨道使它工作谢谢你
猜你喜欢
  • 2016-01-30
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 2013-03-08
  • 2022-12-31
  • 1970-01-01
  • 2015-02-20
相关资源
最近更新 更多