0

I'm not sure how to word this, so please bear with me..

On my main controller, I have a large object containing a bunch of nested geographic information that can be traversed with dot notation like so...

$scope.cData = //large object pulled in from service

// In the view, I can call the entire object or traverse it to return JSON
{{cData}} // Entire object
{{cData.United_States}} // US Data only
{{cData.United_States.Southwest}} // Southwest region only
{{cData.United_States.Southwest.Texas}} // Texas state only

In a child controller, I have a scope that is built up with a bunch of inputs on a UI. So depending on which choices the user has made, all of the variables are watched and concatenated to a controller scope. Based on what the user has chosen, the watch function will alter the "query" variable:

$scope.companyData = "United_States.Southwest"; // User chooses southwest

So the question is, how can i make companyData pass as arguments to the cData object in the view? An incorrect way of looking at it would be like this:

{{$parent.cData + {{companyData}} }}

In other words, I want to use the companyData scope variable to reference where to traverse into the cData scope variable.

sdawson26
  • 139
  • 4
  • 15

2 Answers2

4

I think using approach proposed by alexsanford1 you can improve this using AngularJS functionality:

inject $parse in your controller and then this function will look something like this:

$scope.getNestedProperty = function(obj, propertyExpr) {
    return $parse(propertyExpr)(obj);
}
Alexander Kalinovski
  • 1,409
  • 1
  • 13
  • 19
  • Nice! This solution is much cleaner :) – alexsanford1 Apr 03 '14 at 18:25
  • Wow, this is incredible! Thank you very much! – sdawson26 Apr 03 '14 at 18:33
  • Alexander, is there an easy way to have the value from this function always update a scope variable? For instance, `$scope.datavalues = getNestedProperty($parent.cData, companyData)` I suppose a watch function or something will do the trick? This way, If i use {{datavalues}}, it will update just like {{getNestedProperty(a,b)}} . Does that makes sense? – sdawson26 Apr 04 '14 at 15:28
3

I would suggest defining a function on the scope that does this. You will need to split the string on the dot character and iteratively access nested attributes. I don't think there's a one-liner for that, but check out this post for a function that will work.

It should look something like:

// Function taken from post referenced above
$scope.getDescendantProp = function(obj, desc) {
  var arr = desc.split(".");
  while(arr.length && (obj = obj[arr.shift()]));
  return obj;
}

And in the HTML:

{{ getDescendantProp($parent.cData, companyData) }}
Community
  • 1
  • 1
alexsanford1
  • 3,587
  • 1
  • 19
  • 23