I am trying to make a directive for an easier access to the static datas in my app. In my $rootScope, I have a params object which contains static datas coming from the backend server. The goal of this directive is to access to the params object easy in the html code. There are 2 parameters :
- param-name which contains the name of the requested object
- param-id which contain the key of the object to access
The result is the title attribute of the request object.
In my HTML code, I have
<ng-params param-name="ContactOrigins" param-id="contact.origin_id"></ng-params>
In my JS code, I have :
myApp.directive('ngParams',
function($rootScope){
return{
restrict: 'E',
template : '<span>{{value}}</span>',
scope: {
paramName: '@',
paramId: '='
},
link: function(scope,element,attrs){
var tab = $rootScope.params[scope.paramName];
console.log(scope.paramId);
scope.value = '';
for(var i = 0; i < tab.length; i++) {
if(tab[i]['id'] == scope.paramId) {
scope.value = tab[i]['title'];
}
};
if(scope.value == '')
scope.value = '<em>Not specified</em>'
}
}
}
);
When the page is loaded, the console.log(scope.paramId)
give me an "undefined" result. So it doesn't work properly.
The thing is that the object contact
is loaded asynchronously through an $http request to the backend server. And my idea is that the $http request is not yet resolved and the directive tries to operate with an empty object.
A last additional point : The directive works perfectly when I put an hard coded value in the param-id attribute (param-id="3"
for example).
My first question is : Am I right with my idea ? My second question is : Is there any way to workaround this problem ? Is it possible to postpone the directive compilation until the $http is resolved ?