jgravois
jgravois

Reputation: 2579

How do I make a dynamically named $scope variable?

I have several (over 30) feeder lists which the console.log has several nodes looking like this:

{
   [functions]: ,
   __metadata: { },
   ID: 8,
   Id: 8,
   Title: "SharePoint"
}

So I want to display the name (which in SharePoint that is called Title) of ANY OF THE LISTS rather than the ID by modifying this function to accept a list parameter and dynamically create a $scope."list"[w] variable. It would save me having to duplicate 30 functions that look like this:

$scope.getWebsite = function(id){
    for(w=0; w<$scope.websites.length; w++){
        if($scope.websites[w].ID == id){
        return $scope.websites[w].Title;
        } // end if
    } // end for
};

and call it like this:

<p>{{getValue('division', thisProject[0].Division_ID)}}</p>

I tried this and it didn't work:

$scope.getValue = function( list, id ){
    var dyno = '$scope.' + list;
    for(w=0; w<dyno.length; w++){
            if(dyno[w].ID == id){
            return dyno[w].Title;
            } // end if
        } // end for
    };

Upvotes: 1

Views: 45

Answers (1)

Marc Kline
Marc Kline

Reputation: 9409

Instead of concatenating '$scope.' + list, try this:

var dyno = $scope[list];

Your function would look like this:

$scope.getValue = function( list, id ){
    var dyno = $scope[list];
    for(w=0; w<dyno.length; w++){
      if(dyno[w].ID == id){
          return dyno[w].Title;
      } // end if
    } // end for
};

Plunker

Upvotes: 1

Related Questions