I have an issue where my Angular array items are duplicated when I refresh data (basically on re-calling the method that creates the array), as it adds the same items to the pre-existing array.
This happens when I switch between accounts, by selecting one of the drop down account IDs in my <select>.
This is my HTML code from where I change the account/profile:
<div ng-show="showSelectTwitterAccounts">
<div>
<div id="DropDownBox">
<label for="ViewTwitterProfile">Select Twitter Profile: </label>
<select ng-change="changeTwitterProfile()" ng-model="selectedTwitterProfileID" id="ViewTwitterProfile" ng-options="channelID for channelID in twitterChannels"></select>
</div>
</div>
</div>
This is the method in my Controller that creates the array of profile IDs:
function getChannelProfiles() {
$scope.showSelectTwitterAccounts = true;
GetUserAccessService.returnBrandProfileID().then(function (brandProfileID) {
SocialMediaUserService.channelProfiles().then(function (channelProfiles) {
channelProfiles.forEach(function (channel) {
if (channel.brand_profile_id === brandProfileID && channel.channel_type === 'twitter') {
$scope.twitterChannels.push(channel.id);
}
});
console.log($scope.twitterChannels);
});
});
}
This is the method that gets called when I switch accounts:
$scope.changeTwitterProfile = function () {
$scope.dataModel = DataModelService.showDataLoadingAnimation();
$scope.twitterPageMetrics = {};
$scope.dataContent = false;
$scope.showSelectTwitterAccounts = true;
var twitterID = $scope.selectedTwitterProfileID;
GetFusionDataService.getItems(getRequestURL(twitterID))
.success(function (data) {
handleDataRetrievalSuccess(data);
getChannelProfiles();
})
.error(function (error, status) {
handleDataRetrievalError(error, status);
});
};
I understand why the duplication is happening. The array is not cleared, and I keep pushing the same IDs into the array.
I have tried a couple options to stop this, like adding
$scope.twitterChannels = [];
In the begging of my method that creates the view. This sets the array as an empty array as expected, and the array is recreated without duplicates.
HOWEVER, when I call my $scope.changeTwitterProfile method, everything works as planned, until it is time to create the array again. The array is cleared, and the data call is made to retrieve the data to filter for the array, but before the data is returned, the system steps into my $scope.changeTwitterProfile method, and by this time the array is still empty, and no profile is found. After this, the array gets created as it should.
Apologies for the long explanation - I just wanted to make it clear what i have tried and what happens.
I would appreciate your help.