As a seasoned C#/ASP.NET developer, my company is transitioning to AngularJS for all future front-end web development projects.
I have encountered a specific challenge that I'm trying to solve. I have a SELECT element bound to an array of "email" objects with properties like "id" and "name". Instead of using ng-repeat, I am utilizing ng-options for data binding. My goal is to select an item from the list, click a button, and then remove it from the original list while adding it to a secondary list. Initially, I considered checkboxes but due to the large number of items in the array, my project manager preferred a different approach.
In order to achieve this functionality, I referred to various JavaScript array functions available at: http://www.w3schools.com/jsref/jsref_obj_array.asp
Coming from a C# background, I am finding it challenging to identify the right technique in JavaScript to accomplish this task efficiently. How can I locate the item in the source array, remove it, and insert it into the target array while maintaining alphabetical sorting based on the "name" property?
This leads me to another question regarding the efficiency of my SELECT binding. Currently, when I select an item and click the button, the ng-model attribute is linked to the "id" of the item which requires scanning the array associated with the SELECT element to retrieve the selected item. Is there a way in AngularJS to bind directly to the object itself instead of its "id" so that I can access the selected item without having to scan through the array? Here is the code snippet where I am binding 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>