Search code examples
angularjsangularjs-directiveangularjs-scopeangularjs-ng-if

directive with ng-if not rendering in Angular.js


I'm trying to render a directive whenever I get the search results back. My plan was to keep a scope variable algoliaSearch initially false and whenever I get back search results I change it to true. Then in my view I tried to render the directive based on the value of my variable.

  .directive('searchResults', function () {
    return {
      restrict: 'E',
      templateUrl: 'app/search/directives/templates/searchResults.template.html',
      controller: ['$scope', 'AlgoliaSearchService', function ($scope, AlgoliaSearchService) {
        $scope.hits = [];
        $scope.nbHits = null;
        $scope.algoliaSearch = false;

        AlgoliaSearchService.on('result', results => {
          $scope.algoliaSearch = true;
          $scope.hits = results.hits;
          $scope.nbHits = results.nbHits;
          console.log($scope.algoliaSearch)
        });

      }]
    };
  })

In my view I want to render the directive when I get the search results back

<search-results ng-if="algoliaSearch"></search-results>

But it doesn't seem to work. It doesn't render anything on searching and even console.log($scope.algoliaSearch) doesn't print anything on console. However if i use like

<search-results></search-results>

or

<search-results ng-if="true"></search-results>

Then it renders and the console.log works but that is not the way I want to.
My problem is why it doesn't conditionally render the directive based on my scope variable. I want to make it render conditionally once I get back the search results.
Any help is much appreciated.


Solution

  • Your directive html <search-results ng-if="algoliaSearch"></search-results> is not showing because it's looking for a variable in $scope algoliaSearch before it even renders and executes the directive code. Not only is that variable not in $scope, but it's further not available until that ng-if is true.

    To fix this, your best bet is either to change your ng-if to be something in $scope or, better yet, just have the <search-results></search-results> directive, and for the html in ...searchResults.template.html to contain the boolean switch, something like

    <div class='search-results' ng-if='algoliaSearch'>
      <div ng-repeat='....'>
        <!-- etc -->