angularjsangularjs-directiveangularjs-scopeangularjs-ng-if

ng-keyup firing but not reading properly when used with an ng-if inside a directive template


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?


Solution

  • 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.