Traversing $scope defined by a string

By : TXN_747
Source: Stackoverflow.com
Question!

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);
By : TXN_747


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 at and set. With those you can do this:

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

var newDate = new Date();
_.set($scope, dateRef, newValue);  //set value


Instead of each time accessing Appointment object's ApptDateTime_Date property like this

var dateRef = "Calendar.Scheduling.field.Appointment.ApptDateTime_Date";

you can set following code at one place in your code

var appointment = $scope.Calendar.Scheduling.field.Appointment;

above code holds reference to Appointment object in appointment variable

then you can form dataRef each time you pass as it as parameter

var dateRef = \"+ appointment + ".ApptDateTime_Date" +\";
By : Ravi Teja


There is a way if the first element is the only one to start with that character:

$ a=(asd fgh ijk)
$ echo "${a[@]^[!${a:0:1}]}"
asd Fgh Ijk

This extracts the very first character of the first element, then excludes that character from being uppercased; [!${a:0:1}] expands to [!a], which matches only f and i as the first characters of their elements.

It fails if multiple elements start with the same character, though:

$ a=(asd agh ijk)
$ echo "${a[@]^[!${a:0:1}]}"
asd agh Ijk


This video can help you solving your question :)
By: admin