Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  177] [ 3]  / answers: 1 / hits: 7911  / 10 Years ago, mon, august 4, 2014, 12:00:00

I'm trying to use the jQuery fancy tree plugin with Angular. The source data for the tree comes from an ajax call in my controller. I'm then trying to get that data into my directive and load the tree. Say the service takes 2 seconds to get the data. Heres a cut down version of my code.



HTML



<div tree-view ></div>


SERVICE



angular.module('sc.services', []).
factory('scService', function ($http) {

var scApi = {};

scApi.getsc = function () {
return $http({
url: config.Url.sc
});
};

return scApi;
});


CONTROLLER



angular.module('sc.controllers', []).
controller('scController', function ($scope, scService) {

scService.getsc().success(function (response) {
$scope.sc = response;
});
});


DIRECTIVE



angular.module('sc.directives', [])
.directive('treeView',function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch('sc', function() {
$(element).fancytree({
source: scope.sc
});
});
}
}
});


Jquery loads the fancy tree onto the page (so the directive is being called) but without an data. I also bind the data to a table on the page just to make sure its loading ok and that works. What am I missing?



Is this the correct way to do this?


More From » jquery

 Answers
7

You could just let the directive wait till the data is retrieved. Your watch might get executed once before the data is retrieved, so just check for the value in the watch to make sure it it has been retrieved already. Something like this:-



        link: function (scope, element, attrs) {

var unwatch = scope.$watch('sc', function(v) {
if(v){ // Check if you got the value already, you can be more specific like angular.isObject/angular.isArray(v)
unwatch(); //Remove the watch
$(element).fancytree({
source: v //or same as scope.sc
});
}
});


You could also use ng-if directive on the directive element, provided your directive is of lesser priority than ng-if. You r directive will not render until sc gets defined.



  <div tree-view ng-if=sc></div>


With 1.3.x you could even make use of 1 time binding.



 <div tree-view ng-if=::sc></div>

[#43373] Saturday, August 2, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylanalis

Total Points: 438
Total Questions: 85
Total Answers: 102

Location: Barbados
Member since Sun, Nov 27, 2022
1 Year ago
kylanalis questions
Sat, Oct 2, 21, 00:00, 3 Years ago
Tue, Oct 13, 20, 00:00, 4 Years ago
Thu, Feb 13, 20, 00:00, 4 Years ago
Tue, Jan 7, 20, 00:00, 4 Years ago
;