链接选择框

时间:2013-10-23 09:40:07

标签: javascript angularjs angularjs-directive html-select

我想知道如何使用Angular实现“链接”选择框,就像我们需要设置项目外观顺序一样,例如:

enter image description here

因此,如果我将第一项的外观顺序更改为3,它将自动将第三项'外观顺序交换为1,或者如果我将第二项'外观顺序更改为1,它将首先交换'顺序为2,依此类推。我不希望项目在视觉上改变顺序,我只想分别改变他们的选择框值。

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分: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);
        }
    }
});