I'm an experienced C#/ASP.NET developer and my company is pushing toward AngularJS for all future web front-end development.
I have a specific situation I can't quite figure out. I have a SELECT bound to an array of "email" objects (with properties "id" and "name") and I am using ng-options instead of ng-repeat to do the data binding. This populates the SELECT for me so what I want to do is to select an item from the list, click a button and then remove the item from the list and add it to a secondary list. I was originally going to use checkboxes but the array has a large number of items in it and my project manager didn't like that.
I'm using this as a reference to all the available array functions: http://www.w3schools.com/jsref/jsref_obj_array.asp
Since I'm so used to C#, I don't have the same methods available in JavaScript and I'm having difficulty trying to find the right technique to do this. What's the best way to identify the item in the source array, remove it, and insert it into the target array while keeping it sorted alphabetically by "name"?
This begs the second question. I don't know if I'm binding my SELECT efficiently because when I select an item and click the button, the ng-model attribute is associated with the "id" of the item which is then used to scan the array the SELECT is bound to, to get the item. Since I'm fairly new to AngularJS, and their documentation isn't quite ideal, I was wondering if it is possible to bind to the object instead of it's "id" then access the selected item directly without having to scan the array. Here's my current code which binds to the "id":
JS:
$scope.addEmailToGroup = function(emailID) {
var email = getEmailByID($scope.emails, emailID);
if (email !== null) {
// TODO: Move item from one array to the other
}
};
function getEmailByID(arr, id) {
var email = null;
var length = arr.length;
for (var i = 0; i < length; i++) {
if (arr[i].id === id) {
email = angular.copy(arr[i]);
break;
}
}
return email;
}
HTML:
<select id="emails" class="form-control" data-ng-model="selectedEmailID" name="emails" data-ng-options="email.id as email.name for email in emails"></select>
<button class="btn btn-default" data-ng-click="addEmailToGroup(selectedEmailID)" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>