Eric Mitjans Eric Mitjans - 4 months ago 9
AngularJS Question

Reusing recurrent function in AngularJS

I have a function that keeps repeating itself in my controller.
It looks like this:

//FUNCTION 1

$scope.selectedage = [];
$scope.pushage = function (age) {
age.chosen = true;
$scope.selectedage.push(age);
console.log($scope.selectedage);
};
$scope.unpushage = function (age) {
age.chosen = false;
var index=$scope.selectedage.indexOf(age)
$scope.selectedage.splice(index,1);
console.log($scope.selectedage);
}


//FUNCTION 2

$scope.selectedgender = [];
$scope.pushgender = function (gender) {
gender.chosen = true;
$scope.selectedgender.push(gender);
console.log($scope.selectedgender);
};
$scope.unpushgender = function (gender) {
gender.chosen = false;
var index=$scope.selectedgender.indexOf(gender)
$scope.selectedgender.splice(index,1);
console.log($scope.selectedgender);
}


I have it like 8 times for 8 different arrays.

Is there any way to write it once and reuse it just changing some values?

Answer

You can make a generic function that accepts a value (container) where it needs to write the "value". Like:

$scope.push = function(container, value){
    value.chosen = true;
    container.push(value);
    console.log(container);
}

$scope.unpush = function(container, value){
    value.chosen = false;
    var index = container.indexOf(value)
    container.splice(index, 1);     
    console.log(container);
}

//sample
$scope.push($scope.selectedage, 10);
$scope.push($scope.selectedgender, "Male");