LoginSignup
18
17

More than 5 years have passed since last update.

AngularJSのngRepeatの特殊なプロパティ

Posted at

(The Special Properties of ngRepeat In AngularJS の訳)

今日のネタはAngularJSのドキュメントから直接持ってきましたが、わずかな方々はそのトピックを見落としていることを知っています。

ngRepeatディレクティブ内で特殊なプロパティ(\$firstや\$lastそして\$middle)が利用できます。これらのプロパティはboolean値(\$firstなら最初の要素に対してだけtrueになるなど)が格納されていて、そして、利用できる2つのさらなる特殊なプロパティは\$evenと\$oddです。

そのほかの便利プロパティは\$indexプロパティで、繰り返す要素の各オフセット値を含んでいて0から始まります(全く良いオフセットのように(?))

次の通りのマークアップをこのPlunkerでのライブで表示できます。そのコードは要素が最初と最後に位置するときに\$firstと\$lastを使って、クリッカブルのupとdownプロンプトを表示することを避けるのに使っています。マークアップでもまたクリックされた要素のオフセットを補足するために\$indexを利用しています。

<table>
    <tr ng-repeat="item in items">
        <td>{{item.title}}</td>
        <td><span ng-show="!$first" ng-click="moveUp($index)">up</span></td>
        <td><span ng-show="!$last" ng-click="moveDown($index)">down</span></td>
    </tr>
</table>

次のコントローラと結び付け、矢印に対してクリックすることによってリストの要素を上へ下へ移動できます。

module.controller("mainController", function($scope){
    $scope.items = [
        { title: "Item 1" },
        { title: "Item 2" },
        { title: "Item 3" },
        { title: "Item 4" },
        { title: "Item 5" },
    ];

    var move = function (origin, destination) {
        var temp = $scope.items[destination];
        $scope.items[destination] = $scope.items[origin];
        $scope.items[origin] = temp;
    };

    $scope.moveUp = function(index){            
        move(index, index - 1);
    };

    $scope.moveDown = function(index){                    
        move(index, index + 1);
    };

});
18
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
17