How can I call the link directive function after running the controller code

I try to make the code in the link function after the controller resolves the HTTP call, but before that the link function is called. How can I call the link after $scope.menuHtml ?

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"); } } 
+6
source share
2 answers

I would suggest using scope.$watch() and overwrite your compiled template code. This way, you can make as many requests to the endpoint of the menu as you want, and your template will be recompiled.

Here's more info about the watch: http://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

Here's an updated version that 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"); }); } } 
+6
source

You can do this using async: false

Please use this code instead of code,

 return { restrict: 'A', controller: ['$scope', '$q','$http', function ($scope, $q,$http) { $http({ method: 'GET', url: 'ajax/menu', async: false }).success(function (data) { $scope.menuHtml = generateHtmlMenu(data); })}], link: function(scope, element, attr) { var templateString = scope.menuHtml; var compiledTemplate = $compile(templateString)(scope); compiledTemplate.appendTo("#testD"); } } 
0
source

All Articles