My controller has variables declared on the $scope and two arrays that hold objects: one for available groups and the other for groups the user is already a part of. The addUserToGroups()
function sends a call to the server to add the user to the selected groups. However, I encounter an error stating that the assignedGroups
array is undefined when I try to update the DOM to reflect the changes.
Controller:
spApp.controller('userCtrl',
function userCtrl($scope,userService,groupService){
$scope.users = userService.getUsers();
$scope.selectedAvailableGroups;
$scope.selectedAssignedGroups;
$scope.availableGroups;
$scope.assignedGroups;
$scope.selectedUser = false;
$scope.addUserToGroup = function (){
userService.addUserToGroup($scope.selectedUser, $scope.selectedAvailableGroups)
};
});
I pass objects into the controller function for the service to use. While it works, I wonder if this is the best approach or if I'm creating too many global variables within the controller.
Service:
spApp.factory('userService', function(){
var addUserToGroup = function (selectedUser, selectedAvailableGroups) {
var addToGroupPromises = [];
var selectedGroupsLength = selectedAvailableGroups.length
for (var i = 0; i < selectedGroupsLength; i++) {
addToGroupPromises[i] = $().SPServices({
operation: "AddUserToGroup",
groupName: selectedAvailableGroups[i].name,
userLoginName: selectedUser.domain
});
};
$.when.apply($,addToGroupPromises).done(function (){
for (var i = 0; i < selectedGroupsLength; i++) {
assignedGroups.push(selectedAvailableGroups[i]);
};
alert(selectedUser.name + " added to: " + JSON.stringify(selectedAvailableGroups));
});
};
});
HTML:
<button type="button" ng-disabled="!selectedUser" ng-click="addUserToGroup()">Add User</button>
I am new to Angular and seeking the best way to handle this. Thank you.
EDIT: I tried passing the $scope.assignedGroups into the function, which works, but the DOM doesn't update even though ng-options should be listening for changes. I can see the assignedGroups change in Batarang, but the DOM doesn't reflect it.
<select id="entityAssigned" multiple
ng-model="selectedAssignedGroups"
ng-options="g.name for g in assignedGroups | orderBy:'name'">
</select>