Bot Sundi
Bot Sundi

Reputation: 1

Simplify Angularjs conditionals inside a loop

Is there a better way of doing the following conditionals in a loop in an angularjs controller?

angular.forEach(vm.brgUniversalDataRecords, function (value) {

    if (value.groupValue2 == 1) {
        vm.graphSwitch1 = value.groupValue3;
    };

    if (value.groupValue2 == 2) {
        vm.graphSwitch2 = value.groupValue3;
    };

    if (value.groupValue2 == 3) {
        vm.graphSwitch3 = value.groupValue3;
    };
});

Is there a simplified version?

Thanks.

Upvotes: 0

Views: 55

Answers (1)

Danny
Danny

Reputation: 624

You can create an object that contains a key value pair with your actions.

var Actions = {
    1 : function () { vm.graphSwitch1 = value.groupValue3; },
    2 : function () { vm.graphSwitch2 = value.groupValue3; },
    3 : function () { vm.graphSwitch3 = value.groupValue3; }
};

var action = value.groupValue2;

if (Actions.hasOwnProperty(action)) {
    Actions[action]();
}

Upvotes: 1

Related Questions