2013-10-23 103 views
0

我想知道如何才能實施「鏈接」選擇框有棱有角,就像如果我們需要設置項目出現的順序,例如:鏈接的選擇框

enter image description here

所以,如果我改變第一項的外觀順序爲3它會自動交換第三項'外觀順序爲1,或者如果我更改第二項'外觀順序爲1它將交換第一'順序爲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/

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); 
     } 
    } 
}); 
+0

是的,還不錯。 。 – Cherniv