Angular Listboxes
Copy items from one list to another and back
by Bretto
HTML
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://code.angularjs.org/angular-1.0.0rc7.js"></script>
<div class="container" ng-app="app" ng-controller="MainCtrl">
<h3>Move item from one list to another and back</h3>
<div class="row">
<!-- Here is who is available -->
<div class="span2 well">
<h4>Available: ({{available.length}})</h4>
<ul class="nav nav-list">
<li ng-repeat="n in available" ng-click="move(n, available, assigned)"><a>{{n.name}}</a></li>
</ul>
</div>
<!-- Here is who is assigned -->
<div class="span2 well">
<h4>Assigned: ({{assigned.length}})</h4>
<ul class="nav nav-list">
<li ng-repeat="n in assigned" ng-click="move(n, assigned, available)"><a>{{n.name}}</a></li>
</ul>
</div>
</div> <!-- row -->
<hr>
<h3>Debug</h3>
<div class="row">
<div class="span2">
{{available}}
</div>
<div class="span2">
{{assigned}}
</div>
</div>
<hr>
<div class="alert span4">
<h3>Notes</h3>
<ol>
<li>Sorting would be nice</li>
<li>Undescrore seems useful!</li>
<li>How could this functionality be made generally available in an app?</li>
<li>Why does Chrome keep warning that event.layerX and event.layerY are broken and deprecated in WebKit. They will be removed from the engine in the near future.</li>
</ol>
</div>
</div> <!-- container -->
CSS
.container{padding:1em;}
JavaScript
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.available=[
{"name":"Peter", "id": 1}
,{"name":"Alasdair", "id": 2}
,{"name":"Andie", "id": 3}
,{"name":"Matt", "id":4}
,{"name":"John", "id": 5}
];
$scope.assigned=[];
// Refactored to a single move method
$scope.move=function(n, fm, to){
var idx=_.indexOf(fm, n)
if(idx != -1){
to.push(n);
fm.splice(idx,1);
}
}
/*
// First attempt using two methods
$scope.assign=function(n){
var idx=_.indexOf($scope.available, n)
if(idx != -1){
$scope.assigned.push(n);
$scope.available.splice(idx,1);
$scope.assigned.sort();
}
}
$scope.unAssign=function(n){
var idx=_.indexOf($scope.assigned, n)
if(idx != -1){
$scope.available.push(n);
$scope.assigned.splice(idx,1);
$scope.available.sort();
}
}
*/
});