Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

javascript - How to use a Dynamic Variable to access Scope field - AngularJS

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...