0

I need to make a basic search for some items. I made a simple control, with a button that clears out the search query:

<div class="item item-input item-button-right">
    <i class="icon ion-ios-search placeholder-icon"></i>
    <input type="text"
           placeholder="Search"
           ng-model="search">

    <button class="button button-icon" ng-if="search" ng-click="search = null">
        <i class="icon ion-ios-close-empty"></i>
    </button>
</div>

However the button does not work. search variable is updated properly, but change is not reflected in the view.

After some digging, I wrapped the query string into an object, making a variable search.query:

<div class="item item-input item-button-right">
    <i class="icon ion-ios-search placeholder-icon"></i>
    <input type="text"
           placeholder="Search"
           ng-model="search.query">

    <button class="button button-icon" ng-if="search.query" ng-click="search.query = null">
        <i class="icon ion-ios-close-empty"></i>
    </button>
</div>

Suprisingly, this works as expected: query is cleared out when button is clicked.

How is this possible? Does angular threats wrapped up scope variables differently from those, which are directly in scope?

Kędrzu
  • 2,385
  • 13
  • 22
  • That's because of prototypical inheritance in javascript, check this answer (not mine, just great) http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs – Boris Charpentier Sep 14 '15 at 08:54
  • This is the thing I was searching for :) Thanks very much. – Kędrzu Sep 14 '15 at 09:06

2 Answers2

1

try

ng-click="$parent.search = null"

ng-if creates child scope, so search is bound to scope of ng-if

karaxuna
  • 26,752
  • 13
  • 82
  • 117
0

it's all about scope inheritance, which is based on javascript prototype inheritance.

search - in this case it is just a value, that will be overwritten in scope that is created by ng-if

search.query - in this case it's a link to search object property and it will be changed also for parent scope.

Stepan Suvorov
  • 25,118
  • 26
  • 108
  • 176