Ng-If only working when refreshing the page

1.1k Views Asked by At

I have a problem with ng-if, I am pretty new to angularjs. I want to show/hide a searchbar only on certain views, but it only works after refreshing the page. But it should work, when the view changed.

html:

<div id="searchbarTop" ng-controller="searchbarController">
  <form class="col-md-12 py-1" ng-if="!showSearchbarTop">
    <div class="input-group">
      <input type="text" class="form-control typeahead" id="query" 
        placeholder="Search for folders or workflows..." data- 
        provide="typeahead" autocomplete="off" ng-wflist="workflowList" wf-search/>
    </div>
  </form>
</div>

controller:

ProjectX.controller("searchbarController", function($scope,$http,$location) {
    $scope.$root.showSearchbarTop = $location.path() === "/";

       ...
});

Hope someone can explain me, which mistake I made.

1

There are 1 best solutions below

0
Adnan Sharif On BEST ANSWER

You are using showSearchbarTop as an attribute which is initialized only at the beginning of the page load. That's why, you need to use it as a function.

See the following code

var ProjectX = angular.module('', []);
ProjectX.controller("searchbarController", function($scope, $http, $location) {
  $scope.$root.showSearchbarTop = function() {
    return $location.path() === "/";
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div id="searchbarTop" ng-controller="searchbarController">
  <form class="col-md-12 py-1" ng-if="!showSearchbarTop()">
    <div class="input-group">
      <input type="text" class="form-control typeahead" id="query" placeholder="Search for folders or workflows..." data- provide="typeahead" autocomplete="off" ng-wflist="workflowList" wf-search/>
    </div>
  </form>
</div>