javascriptangularjsionic-frameworkionic-view

"ng-click" not working out of "ion-content" in Ionic framework


I have an input box with the ng-model attribute in my ionic based application. The code inside the ion-content tag:

<ion-content class="padding">
  <input ng-model="myNumber" type="number" placeholder="Enter number">
</ion-content>

And in the footer-bar I have this:

<div class="bar bar-footer bar-balanced" style="background-color: #00368C !important; color: #fff;">
    <div class="title">
      <button ng-click="submit(myNumber)" class="button button-clear">Submit</button>
    </div>
</div>

The alert result is undefined.

NOTE: when I put the button inside the ion-content it works fine. (It means js codes works fine)

Any idea?


Solution

  • The reason behind your problem is, ion-content directive does create a child scope which is prototypically inherited from the parent scope. So by placing myNumber in input ng-model does get added inside the scope of ion-content, which is different that the controller myNumber number scope variable.

    To make it working you need to follow dot rule while defining ng-model, so that prototypal inheritance rule will get follow(it works on reference type variable). So create an new object inside a controller and do assign all ng-model variable into it. like below

    $scope.model = {};
    

    And then put all the properties you wanted to use on view like $scope.model.myNumber & while using it on view use it like model.myNumber

    Markup

    <ion-content class="padding">
      <input ng-model="model.myNumber" type="number" placeholder="Enter number">
    </ion-content>
    
    <div class="bar bar-footer bar-balanced" style="background-color: #00368C !important; color: #fff;">
        <div class="title">
          <button ng-click="submit(model.myNumber)" class="button button-clear">Submit</button>
        </div>
    </div>
    

    Detailed explanation can be found in this answer

    More elegant way of doing it would be using controllerAs approach.