Load directive after AJAX call

I created a pagination directive that takes two arguments; current page and total number of pages.

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

The problem is that I will know the value of numberOfPages after calling AJAX (via ng-resource). But my directive is already done before the AJAX call is made.

 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 controller template until the AJAX call completes.

In Plan B, a template with a template for directives will be added when an AJAX call is made.

I am stuck in developing both scenarios.

+8
angularjs angularjs-directive angularjs-resource
source share
3 answers

You need to wait for the value using the $watch function, for example:

 <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 } }); } }; } ]); 

Interoperable: Your directive may use an isolated scope, but, nevertheless, the same principle is worth it.

+9
source share

But is it not possible to simply prevent rendering until everything is done.

  • I think ng-if will do this, contrary to ng-show / ng-hide, which just change the actual display
+13
source share

If you use resolve from ui-router , you can enter meta or meta.number_of_pages in your controller before it gets rendered.

 //routes.js angular.module('app') .state('some_route', { url: '/some_route', controller: 'MyController', resolve: { meta: ['MyResource', function (MyResource) { return MyResource.query({ "page": $scope.page, "per_page": 100 }, function (response) { return response.meta; }); }] } }); //controllers.js app.controller('MyController', function ($scope, $routeParams, meta) { $scope.page = +$routeParams.page || 1, $scope.numberOfPages = meta.number_of_pages; }); 
0
source share

All Articles