# Angular directive to fetch resources to fill a table

I created a directive that solves my immediate problem, but I'm trying to find ways to make it more reusable.

My immediate problem was, I have a table and needed to fill in one of the columns with data from an http request. I passed an object (dir.provider.resource) and a string (attr) into the directive, made a GET request with its href, and then displayed the value gotten from resource[attr].

HTML:

<td class="col-status" ng-if="resource">
<get-resource-property passedResource="dir.provider.resource" attr="status"></get-resource-property>
</td>


Directive:

angular.module('myApp')
.directive('getResourceProperty', function (\$http) {
return {
restrict: 'E',
replace: true,
scope: {
passedResource: '=',
attr: '='
},
template: '<td>{{result}}</td>',
var resource = scope.passedResource;
var attr = scope.attr;

if (resource) {
http.get(resource.href)
.then(function (resource) {
setScope(resource);
});
}

function setScope(resource) {
scope.result = resource[attr];
if (attr === 'status') {
//do specific stuff with the status here
var color = resource[attr] === 'ON' : 'green' ? 'red';
element.css("color", color);
}
};
}
}
});


It would be really useful to make this more reusable, as I have to work with a lot of nested resources in my project. Take the example below:

{
href: "httsp://site.com/resource/12345",
otherResource: {
href: "https://site.com/other-resource/678910"
},
relatedResource: {
href: "https://site.com/resource/12345/related-resource/"
},
...
}


If I want to access a property in relatedResource, I have to make a GET request before I can do so. Sometimes I just need to get one value (like in the above example, I just need to get a nested resource's status), so I can see this being useful in these types of cases..

Am I thinking about this right, or am I missing something obvious? Does anything stand out from the code that looks off? (I am new to angular, so any tips would be great!)

• how do you pass the nested resource? In other words, how do you know when to call a nested resource and when not to? – tanmay Jan 7 '17 at 6:05