Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load directive after AJAX call

I have build a directive for pagination that takes two arguments; the current page and the total number of pages.

<pagination page="page" number-of-pages="numberOfPages"></pagination>

The issue is that I will only know the value of numberOfPages after an AJAX call (through ng-resource). But my directive is already rendered before that the AJAX call is done.

app.controller('MyController', function ($scope, $routeParams) {
    $scope.page = +$routeParams.page || 1,
    $scope.numberOfPages = 23; // This will work just fine

    MyResource.query({
        "page": $scope.page,
        "per_page": 100
    }, function (response) {
        //This won't work since the directive is already rendered
        $scope.numberOfPages = response.meta.number_of_pages;
    });
});

I prefer to wait with the rendering of my controllers template until the AJAX call is finished.

Plan B would be to append the template with the directives template when the AJAX call is done.

I'm stuck working out both scenarios.

like image 992
Erik Nijland Avatar asked Feb 07 '15 22:02

Erik Nijland


2 Answers

But isn't it possible to just prevent the rendering until all is done

  • I think ng-if would do that, contrary to ng-show/ng-hide which just alter the actual display
like image 111
Manube Avatar answered Nov 03 '22 13:11

Manube


You have to wait for the value using a $watch function like:

<div before-today="old" watch-me="numberOfPages" >{{exampleDate}}</div>

Directive

angular.module('myApp').directive('myPagingDirective', [
  function () {
    return {
        restrict: 'A',   
      link: function (scope, element, attr) {


        scope.$watch(attr.watchMe,function(newValue,oldValue){
                //check new value to be what you expect.
             if (newValue){           
                  // your code goes here
             }
        });
      } 
    };
  }
]);

Imporant: Your directive may use an isolated scope but even so the same principle stands.

like image 28
Dalorzo Avatar answered Nov 03 '22 15:11

Dalorzo