I am looking to create a dynamic template using data from a database (specifically Firebase/angularFire). The structure of the template will be determined by the tag property within each object retrieved with angularFire. Initially, I tried:
var imgTemplate = function(tag){
return '<'+tag.tag+' class="{{ tag.classes }}" src="{{ tag.content }}" alt="{{ tag.alt }}">';
};
var txtTemplate = function(tag){
return '<'+tag.tag+' class="{{ tag.classes }}">{{ tag.content }}</'+tag.tag+'>';
};
However, this approach did not work as expected because tag.tag was undefined since the compile function runs before angularFire fetches the data and binds it. Here is my second attempt:
var imgTemplate = function(tag){
return '<{{tag.tag}} class="{{ tag.classes }}" src="{{ tag.content }}" alt="{{ tag.alt }}">';
};
var txtTemplate = function(tag){
return '<{{ tag.tag }} class="{{ tag.classes }}">{{ tag.content }}</{{ tag.tag }}>';
};
This solution only partially renders the template:
<{{ tag.tag }} class="{{ tag.classes }}">{{ tag.content }}
for each 'tag' element iterated over with ng-repeat instead of generating the actual HTML.
This is the compile function of my directive:
compile: function(templateElem, directiveAttrs){
var tag = directiveAttrs.tag;
if(tag.tag === 'img'){
var img = angular.element(imgTemplate(tag));
templateElem.replaceWith(img);
}else{
var txt = angular.element(txtTemplate(tag));
templateElem.replaceWith(txt);
}
},
The data is fetched from Firebase in a controller of an angular.ui.router's state:
.state("siteNav.sideNav.content", {
url: '/:lang/:view/:contentID/:index',
views:{
'@': {
templateUrl: '/views/content.html',
controller: function($scope, angularFire){
var stateParams = $scope.$stateParams;
console.log(stateParams.lang);
var url = 'https://example.firebaseio.com/'+stateParams.lang+'/content/'+stateParams.view+'/'+stateParams.contentID;
angularFire(new Firebase(url), $scope, 'tags');
}
}
}
}
The content of template content.html is as follows:
<div ng-repeat="tag in tags">
<acms-view tag="tag"></acms-view>
</div>
- I require the three-way binding functionality provided by angularFire.
- The tag must come from Firebase, so I cannot use a literal value instead.
How can I make sure that the 'tag' property is populated before the compile function uses it for comparison or value assignment?
I cannot use the angularFire service within the compile function as there is no scope to bind the fetched data to.
Even though angularFire does not work within the linking function, using Firebase's JavaScript API could be a potential solution. However, how would I achieve the three-way binding offered by angularFire?
Thank you for your assistance
Jared