0

I need some help regarding my very first AngularJS project (after the official tutorial). It started well, since I was able to control my form, submit my ajax request and display the results as I want with a pagination... Isn't that great? But now I try to make an ajax loader. I think it would have been possible using ng-show directive, but I'd like to make it as generic as possible so I can re-use it on other projects.

So I started to create a directive (following this: Angularjs loading screen on ajax request). Now everything works as I want, except that the ajax loader is never displayed.

It seems that my directive doesn't check the loading parameter. I have the feeling I missed something about the scope.

Here's my code (simplified):

(function() {
var app = angular.module('querygen', []);

app.controller('QuerygenController',['$http', function($http){

    this.loading=false;

    this.getQueries = function(page){
        this.loading = true;
        querygen = this;
        $http.post('/action.php', data).success(function(data){
            querygen.loading = false;
        }).error(function(data){
            querygen.loading=false;
            alert('An error occured.');
        });
    };      

}]);  

app.directive('loading', function () {
  return {
    restrict: 'E',
    replace:true,
    template: '<div class="loading"><img src="images/loader.gif" alt="Loading..." /></div>',
    link: function (scope, element, attr) {
          scope.$watch('loading', function (val) {                  
              if (val)
                  element.show();
              else
                  element.hide();
          });
        }
      };
    });

})();

My HTML:

 <div ng-controller="QuerygenController as querygenCtrl">
    <loading></loading>
    <div ng-show="!querygenCtrl.loading">
        <div ng-repeat="query in querygenCtrl.queries">        
            {{query}}
        </div>
    </div>
 </div>

Also, once my issue solved, if I put the directive into another module, and add the new module as a dependency of "querygen", will it work as it is?

Community
  • 1
  • 1
Neow
  • 125
  • 6
  • I am unsure of your use of "this" in your controller. I was under the impression that scope.$watch should only be use on other scope variables but I can't find the docs to support that right now. Have you tried making 'loading' a scope variable? – cjkenn Feb 23 '15 at 16:04

1 Answers1

0

I post the answer. MapOfVeins was right. Updating this.loading to $scope.loading solved my issue. There was definitively something I missed regarding this/$scope. Thank you!

Neow
  • 125
  • 6