Ng-If 仅在刷新页面时有效

Ng-If only working when refreshing the page

我对 ng-if 有疑问,我是 angularjs 的新手。我想 show/hide 仅在某些视图上使用搜索栏,但它仅在刷新页面后才有效。但是当视图改变时它应该可以工作。

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>

控制器:

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

       ...
});

希望有人能解释我,我犯了什么错误。

您正在使用 showSearchbarTop 作为仅在页面加载开始时初始化的属性。这就是为什么,您需要将其用作函数。

看下面代码

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>