从JSON中拆分字符串并以ng-repeat显示

时间:2016-09-28 11:49:03

标签: angularjs angularjs-ng-repeat

<div ng-controller="countryCtrl">
  <div class="m-b-20" ng-repeat="val in records">
    {{val.Country}} <br>
  </div>
</div>

var app = angular.module('app', [])
  .controller('countryCtrl', ['$scope', function($scope) {
    $scope.records = [{
      "Country": "Germany,France,UK,Japan"
    }, {
      "Country": "Sweden,Australia,USA"
    }, {
      "Country": "Mexico,Colombia,Brazil"
    }, {
      "Country": "Austria,UAE,Kenya"
    }]
  }])

不是在字符串中显示国家/地区,而是需要拆分国家/地区并将其显示为项目符号。

3 个答案:

答案 0 :(得分:3)

使用ng-keyup

<div class="m-b-20" ng-repeat="val in records">
    <ul>
        <li ng-repeat="country in val.Country.split(',')">{{ country }}</li>
    </ul>
</div>

string.split method

答案 1 :(得分:2)

重复次数越少,过滤效果越好。处理控制器中的更改,以便模板不会看太多。处理它的简单方法是创建一个指令并在添加它时将其拆分。 Fiddle is here。步骤很简单:

更新模板

<div class="m-b-20" ng-repeat="val in ::records">
    <country my-country="{{::val.Country}}"> </country>
</div>

添加新指令。随意用您的标记替换模板:

  angular.module('app').directive('country', CountryDirective);

  /* @ngInject */
  function CountryDirective ($compile, $rootScope) {
    return {
      restrict: 'E',
      replace: true,
      template:'<ul><li ng-repeat="c in ::countries">{{c}}</li></ul>',
      controller: CountryDirectiveController,
      scope:{
        'myCountry':'@'
      }
    };


    /* @ngInject */
    function CountryDirectiveController ($scope) {


      onCountryChange();

      /*
       //You only need this if you dont use  '@' if you need = or < you might need to take special care to make sure its bound.  
      $scope.$watch('myCountry', onCountryChange);
      */
      function onCountryChange(){
         $scope.countries = ($scope.myCountry || '').split(',').map(function(i){ return i.trim()});
      }
    }
  }

答案 2 :(得分:0)

您可以通过创建一个过滤器来通过提供拆分字符来分割字符串,从而以更有棱角的方式执行此操作。

在你的HTML中

<div ng-app="app" ng-controller="countryCtrl">
  <div class="m-b-20" ng-repeat="val in records">
     <ul>
        <!-- Use the filters to split the string values -->
        <li ng-repeat="country in val.Country | split:','">{{ country }}</li>
     </ul>
   </div>
</div>

过滤

app
   .filter('split', function() {
       return function(input, separator) {
           // returns an array
           return input.split(separator);
       }
    });