0

アイテムの表示順序を設定する必要がある場合など、Angular で「リンクされた」選択ボックスをどのように実装できるか疑問に思っていました。たとえば、次のようになります。

ここに画像の説明を入力

したがって、最初のアイテムの出現順序を 3 に変更すると、3 番目のアイテムの出現順序が 1 に自動的にスワップされます。または、2 番目のアイテムの出現順序を 1 に変更すると、最初のアイテムの出現順序が 2 にスワップされます。アイテムの順序を視覚的に変更したくありません。選択ボックスの値をそれぞれ変更したいだけです。

4

2 に答える 2

1

SO で解決策が見つかると確信していましたが、運がありませんでした。だから私はここに私の解決策を投稿します.

意見:

<ul ng-controller="Ctrl">
    <li ng-repeat="item in items">        
        <label>
            Item {{$index}}. Order of Appearance:
            <select ng-model="item.order" ng-options="o.order as (o.order+1) for o in items"  ></select> {{item}}
        </label>
    </li>
</ul>

コントローラ:

function Ctrl( $scope , $filter ){

    $scope.items = [ { order:0 } , {  order:1 }  , { order:2 } ]; // Default order

    for(var i in $scope.items){

        (function( item ) {            // Tricky part , need to use IIFE

            $scope.$watch( function(){ return item; }, function(n,o){

                if(n == o) return;

                var rel = $filter('filter')($scope.items, function( item_for_filtering ){

                            // Filtering previous element with same order

                     return (item_for_filtering.order == n.order && item_for_filtering!= n)

                } )[0];

                if(rel)
                   rel.order = o.order;   // Giving prev element new order 

            },true );

        })( $scope.items[i] );
    }
}

作業例: http://jsfiddle.net/cherniv/D3zd8/

于 2013-10-23T09:40:06.747 に答える
1

ディレクティブを使用して、これにひねりを加えます。

<ol ng-app="app" ng-controller="MainCtrl">
  <li ng-repeat="item in items | orderBy:'position'">
    {{ item.name }}
    <select positoner ng-model="itemPosition" ng-options="p for p in positions()"></select>
  </li>
</ol>

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

app.controller('MainCtrl', function ($scope) {
  $scope.items = [
    { name: 'First', position: 1 },
    { name: 'Second', position: 2 },
    { name: 'Third', position: 3 }
  ];

  $scope.positions = function () {
    var arr = [];

    angular.forEach($scope.items, function (item) {
        arr.push(item.position);
    });

    return arr;
  }
});

app.directive('positoner', function () {
    return {
        link: function (scope, el, attr){
            scope.$watch('itemPosition', function (n, o) {
                if (n === o) return;

                angular.forEach(scope.items, function (item) {
                    if (item.position === n) item.position = o;
                });

                scope.item.position = n;
            });

            scope.$watch('item', function (n, o) {
                scope.itemPosition = scope.item.position;
            }, true);
        }
    }
});
于 2013-10-23T16:15:35.877 に答える