1

I am trying to have a variable string, and access the matching $scope.field but it is undefined and not returning what I am expecting. What am I doing wrong, or is this not possible?

$scope.selectedHolidayA = "Christmas"
$scope.selectedHolidayB = "NewYears"

var HA = "selectedHolidayA";
var HB = "selectedHolidayB";

I want to get the same result as $scope.selectedHolidayA = "Christmas". But I am getting undefined.

I tried these but no luck.

console.log("Test 1", $scope["HA"]);   //I want these to return "Christmas"
console.log("Test 2", $scope[HA]);     //Currently returns undefined
console.log("Test 3", $scope.HA);
        

Is it possible to pass variables, if so how? Thanks!

1 Answer 1

0

Use "Test 2":

$scope = {};

$scope.selectedHolidayA = "Christmas"
$scope.selectedHolidayB = "NewYears"

var HA = "selectedHolidayA";
var HB = "selectedHolidayB";

console.log($scope[HA]+' and '+$scope[HB]);

console.log("Test 2", $scope[HA]);

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh thanks! The example I actually tried originally didn't have HA with quotations marks, so it was undefined. It was var HA = selectedHolidayA; before by mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.