sourcecode

AngularJs ng-repeat, 마지막 항목 앞에 'and'로 구분된 쉼표

codebag 2023. 3. 9. 22:02
반응형

AngularJs ng-repeat, 마지막 항목 앞에 'and'로 구분된 쉼표

아이템 리스트가 있는데...

$scope.Users =[{
    UserName: ''
}];

제 의견으로는, 저는 단지 4개의 아이템이 있다고 가정하고, 이렇게 리스트업 하고 싶습니다.$scope:Users

Username1, Username2, Username3 and Username4

<span data-ng-repeat="user in Users">{{user.Username}}</span>{{$last ? '' : ', '}}

위의 표현식은 기본적으로 각 항목 뒤에 쉼표를 추가하여 올바르게 작동합니다.

제 문제는 어떻게 하면 I/O에and키워드를 입력하면 다음과 같이 됩니다.

Username1, Username2, Username3 and Username4

다음 대신:

Username1, Username2, Username3, Username4

$last는 truthy 값입니다.참인지 거짓인지, 마지막 요소 지수를 포함하지 않습니다.

아래 표현이 너의 문제를 해결해 줄 것 같아.

<p><span ng-repeat="user in Users">
            {{user.Username}} {{$last ? '' : ($index==Users.length-2) ? ' and ' : ', '}}
  </span></p>

또한 ng-repeat 요소 내에서 $last로 표현하고 외부에서는 표현하지 않도록 하십시오.

아래 작동 바이올린을 확인해 주세요.

http://jsfiddle.net/hrishi1183/Sek8F/2/

이것이 해결책 중 하나일 수 있습니다.

<span data-ng-repeat="user in Users">{{user.Username}}<font ng-show="!$last">,</font></span>
<span ng-repeat="user in Users">{{$first ? '' : $last ? ' and ' : ', '}}{{user.Username}}</span>

무언가를 추가하는 대신 그 앞에 추가합니다.사용할 수 있습니다.$first첫 번째 거 빼고요.그 후 를 사용할 수 있습니다.$last쉼표 대신 "and"를 추가합니다.

명확성을 높이려면 , 및 에 쉼표를 사용합니다.

빌 게이츠는 600만 달러를 Username1, Username2, Username3에 기부한다.

빌 게이츠는 600만 달러를 Username1, Username2, 및 Username3에 기부합니다.

연속 쉼표가 없으면 각 사용자에게 동일한 공유가 주어지는 것을 문장이 명확하게 나타내지 않습니다.

<span ng-repeat="user in Users">
     {{user.Username}}{{$last ? '' : ($index==Username.length-2) ? ', and ' : ',&nbsp;'}}
</span>

출력:

Username1, Username2, Username3, and Username4

텍스트 출력만 필요한 경우 사용자 지정 필터를 사용합니다.ng-repeat:

<span>{{Users | humanizedUserList}}</span>

필터 코드는 다음과 같습니다(Lodash 사용).

app.filter('humanizedUserList', function() {
  return function(users) {
    var last_users = _.last(users, 2);
    return _.reduce(users, function(out, user, idx, users) {
      out += user.UserName;

      if(user === last_users[1]) { // last entry
        return out;
      }
      else if(user === last_users[0]) { // second to last entry
        return out + ', and ';
      }
      else {
        return out + ', ';
      }
    });
  };
}

당신은 그 해킹적인 사용을 피할 수 있을 것이다.$last을 벗어나서ng-repeat및 삼원 연산자 - 응용 프로그램의 다른 부분에 대한 재사용 가능성을 추가합니다.

오늘 이 문제에 직면했습니다만, 리스트 아이템의 형식을 문장내에서 지정할 필요가 있는 경우가 있습니다(굵은 글씨로 된 아이템이나 링크 등).필터에서 문자열을 출력하는 것만으로는 작동하지 않습니다.처음에는 ng-bind-html을 사용하여 HTML을 필터에서 출력하려고 했지만, 유연성이 부족했습니다.

목록 항목 사이에 구분자를 추가하는 ng-repeat 내에서 사용할 수 있는 지시문을 작성하게 되었습니다.문제는 $first, $last 및 $index(원래 배열이나 길이 아님)에만 액세스할 수 있었다는 것입니다.

솔루션:

var app = angular.module('app', []);
app.directive('listSeparator', function() {
  return {
    replace: true,
    template: '<span>{{ separator }}</span>',
    link: function(scope, elem, attrs) {
      scope.$watchGroup(["$index", "$first", "$last"], function() {
        if (scope.$first)
          scope.separator = "";
        else if (scope.$last && scope.$index == 1)
          scope.separator = " and ";
        else if (scope.$last)
          scope.separator = ", and ";
        else
          scope.separator = ",";
      })
    }
  }
})
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<div ng-app="app">
    Click a button to see the formatted list.
    <button ng-click="myArray = ['one']">One item</button>
    <button ng-click="myArray = ['one','two']">Two items</button>
    <button ng-click="myArray = ['one','two','three']">Three items</button><br>
    <span ng-repeat="item in myArray"><list-separator></list-separator>
        <strong>{{item}}</strong></span>

</div>

맛있게 드세요!

언급URL : https://stackoverflow.com/questions/26926345/angularjs-ng-repeat-comma-separated-with-and-before-the-last-item

반응형