Trying to find the best practices with AngularJS. Here's the deal:
There are two different pages with forms where each of them have their own form fields. But there is a one common functionality on both of the forms: they have an autocomplete field which the user can use to select multiple email addresses that exist in the system.
The selected email addresses are stored to the model/scope so that they can be shown on the HTML page. Here's an example:
<div ng-controller="MyCtrl">
<form ng-submit="selectCurrentEmail()" novalidate>
<input type="text"
class="form-control"
ng-model="responsiblePerson" />
<input type="submit" value="Add" />
<div ng-repeat="email in formData.selectedEmails">
<div>
{{email}} <a href="" ng-click="removeEmail(email)">x</a>
</div>
</div>
</form>
</div>
and the angularjs part:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.formData = {selectedEmails: []};
$scope.selectEmail = function(email) {
if (email != null && $.inArray(email, $scope.formData.selectedEmails) == -1) {
$scope.formData.selectedEmails.push(email);
$scope.responsiblePerson = null;
}
};
$scope.removeEmail = function(email) {
var index = $.inArray(email, $scope.formData.selectedEmails);
if (index != -1) {
$scope.formData.selectedEmails.splice(index, 1);
}
};
$scope.selectCurrentEmail = function() {
$scope.selectEmail($scope.responsiblePerson);
};
}
(doesn't contain the autocomplete since it's not the main issue here..)
This all works fine, but I don't want to repeat the same logic in both of the controllers. What I would like to have is a service or a base controller that can take care of setting and removing the selected email addresses. And when the user is done, the scope would have just the selected email addresses.
So, do you think there's a good way to generalize the three functions in the scope? Any ideas making this better?