Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing $scope defined by a string

I have a string that in being passed in as an attribute ("Calendar.Scheduling.field.Appointment.ApptDateTime_Date") that defines the location of the variable in the $scope. Is there a better way to get to the location of the value in the scope than to loop through the child objects. I was hoping there would be an xpath type declaration that could be used

The $scope layout is as follows:

$scope : {
    	Calendar: {
    		Office: {
    			Name: "Dr. Suess",
    			Address: "1234 Main St.",
    			City: "Whoville"
    		},
    		Scheduling: {
    			LastName: "Doe",
    			FirstName: "Jane",
    			Appointment: {	
    				"CallDateTime_Date" : "08/05/2016",
    				"CallDateTime_Time" : "10:24 AM",
    				"ApptDateTime_Date" : "10/12/2016",
    				"ApptDateTime_Time" : "06:00 AM"
    			}
    		}
    	}
    };

Can I get to the $scope. Calendar.Scheduling.field.Appointment.ApptDateTime_Date without itearting through the child[s].

var dateRef = "Calendar.Scheduling.field.Appointment.ApptDateTime_Date";
tempString = tempString.replace(/\./g, '","');
var ar = JSON.parse('["' + tempString + '"]');

var currentRef = $scope;
ar.forEach(function (entry) {
    currentRef = currentRef[entry];
});

currentRef = new Date($scope.apptDate);
like image 291
TXN_747 Avatar asked Mar 15 '26 01:03

TXN_747


1 Answers

My recommendation would be to use lodash. Lodash is a very handy library with a bunch of useful utility functions. Two functions it provides are get and set. With those you can do this:

var dateRef = "Calendar.Scheduling.field.Appointment.ApptDateTime_Date";
var date = _.get($scope, dateRef);  //get value

var newDate = new Date();
_.set($scope, dateRef, newValue);  //set value
like image 140
Dustin Hodges Avatar answered Mar 16 '26 14:03

Dustin Hodges