I have developed a custom dropdown option selector which is functioning well. It includes functions to fetch data from a specified URL in order to populate a list.
However, the issue arises when I attempt to reuse this component in a different section of my application with a separate dataset. This results in duplication of data and multiple executions of the controller's functions.
My understanding is that there are two main problems at hand. Firstly, services act as singletons, meaning that when the function to populate data is executed, it simply appends the new data to the existing dataset due to the presence of only one instance of the service.
Secondly, controllers do possess instances, leading to the execution of functions in each instance, thereby causing repetition.
The simplest solution might be to duplicate the component and assign it a different name. While this may resolve the issue temporarily, it would result in creating multiple copies of the same component if reusability for multiple instances is desired, which is not ideal.
Coming from an object-oriented programming background in Java, I understand that I might be applying OOP techniques in a language that does not fully support them ;)
Therefore, I realize the necessity to rethink my approach, but I seem to have hit a barrier. What would be the best way to tackle this problem?
Below is a JSFiddle link to provide better insight into what I am encountering:
var app = angular.module('myApp',[]);
app.directive('mySelector', function () {
return {
scope: {
mydata: '='
},
restrict: 'EA',
template:'<select ng-model="timePeriodSelection" ng-options="timePeriodOption.name for timePeriodOption in timePeriodOptions"><option value="">Choose time period</option></select>',
controller: function($scope, myService) {
//$scope.name = 'Superhero';
console.log('test',$scope.mydata);
myService.setData($scope.mydata);
$scope.timePeriodOptions = myService.getData();
console.log('test2',myService.getData());
}
};
});
app.factory('myService', function() {
var _data=[];
return {
setData: function(value){
for (var a=0;a<value.length;a++){
_data.push(value[a]);
}
},
getData: function(){
return _data
}
}
});
https://jsfiddle.net/devonCream/ess9d6q6/
Unfortunately, I cannot share the actual code for confidentiality reasons. However, imagine that instead of passing in a hardcoded value, I am fetching data from a URL through a service and storing it in an array within the factory. With each execution, the data keeps accumulating! This code serves as a demonstration.