0

I have a directive and it works fine in a way such that when I type something the search() scope function inside my directive fires and sets $scope.query with the input text.

here is the directive template

<div class="container">
    <div class="system-filter-header">
        <div class="no-gutter">
            <div class="system-search-wrapper search-wrapper-width">
                <i ng-click="search($evt)" class="fa fa-search"></i>
                <input type="text" ng-keyup=search($evt)  class="search pull-left suggesstions-styles"
                ng-model="query" ng-attr-placeholder="Search...">
            </div>
        </div>
    </div> 
</div>

here is the scope function which gets triggered

$scope.search = function() {
          console.log($scope.query.length)
}

But when I used an ng-if="true" in first line of template (true used for generalizing only, I want to do a different conditional check inside ng-if) such that,

<div class="container" ng-if="true">

still the search gets triggered but the console.log gives always 0 and it doesn't seem to update the $scope.query value as it stays as $scope.query = '' throughout the typing.

EDIT Here is a an example codepen with almost similar behaviour. The problem is with the searchBox directive and I have added ng-if=true to the template but searching doesn't work. When I remove the ng-if searching works fine.

Any reason for this?

cmgchess
  • 7,996
  • 37
  • 44
  • 62
  • Can you post a little more of the code from your directive's controller or link function? That might help us to better help you debug. Thanks! : ) – Gerald LeRoy Feb 04 '22 at 06:34
  • @GeraldLeRoy hello my directive controller has `$scope.query = ''` initialized and then there is this function `$scope.search` which manipulates the value of query. it was working as expected until i put the ng-if – cmgchess Feb 04 '22 at 06:39
  • 1
    @GeraldLeRoy hi I added a demo link as well – cmgchess Feb 04 '22 at 09:33
  • As an addendum to my answer, I strongly recommend you get off AngularJS 1.0.x. Even if an upgrade to Angular2+ isn't feasible, you should do what you can to get to 1.8 – Jacob Stamm Feb 04 '22 at 17:13
  • @JacobStamm im working on an old long running project which uses 1.4 so I dont have a choice :D – cmgchess Feb 04 '22 at 17:43

1 Answers1

1

Rule of thumb in AngularJS: your ng-model should always include a dot. Otherwise AngularJS directives that create child scopes (like ng-if or ng-repeat) will create a duplicate property on that child scope instead of the parent scope. Following the controllerAs convention completely mitigates this behavior.

Jacob Stamm
  • 1,660
  • 1
  • 29
  • 53