Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs directive to get data from ajax call in controller

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?

like image 593
garethb Avatar asked Dec 20 '25 02:12

garethb


1 Answers

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>
like image 56
PSL Avatar answered Dec 22 '25 14:12

PSL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!