I'm trying to render code in the link function after the controller resolves the http call but the link function is called before that. How can I call link after $scope.menuHtml
has been set?
HTML:
<div id="testD" nav-menu-output="parseMenuJsonAndOutPutMenu()"></div>
DIRECTIVE:
return {
restrict: 'A',
controller: ['$scope', '$q','$http', function ($scope, $q,$http) {
$http.get('ajax/menu' ).then(function (data) {
$scope.menuHtml = generateHtmlMenu(data);
});
}],
link: function(scope, element, attr) {
var templateString = scope.menuHtml;
var compiledTemplate = $compile(templateString)(scope);
compiledTemplate.appendTo("#testD");
}
}
I would suggest using scope.$watch()
and rerunning your compiled template code on that. This way you can make as many requests to the menu endpoint as you want and your template will be recompiled.
Here's more information about watch: http://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch
Here's an updated version which should work properly:
return {
restrict: 'A',
controller: ['$scope', '$q','$http', function ($scope, $q,$http) {
$http.get('ajax/menu' ).then(function (data) {
$scope.menuHtml = generateHtmlMenu(data);
});
}],
link: function(scope, element, attr) {
scope.$watch('menuHtml', function() {
var templateString = scope.menuHtml;
var compiledTemplate = $compile(templateString)(scope);
compiledTemplate.appendTo("#testD");
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With