Search code examples
javascriptjqueryonsen-ui

Javascript not working in ons-template of Onsen UI


I'm trying to integrate panzoom in Onsen UI to allow zooming of images. However it only zoom if it put in under ons-page. It won't work under ons-template. This is my code which is not work.

<body ng-controller="AppController">    

  <ons-navigator var="navi">
    <ons-page>
      <ons-toolbar>
        <div class="center">App</div>
      </ons-toolbar>

      <ons-list ng-controller="MasterController">
        <ons-list-item modifier="chevron" class="item" ng-repeat="item in items" ng-click="showDetail($index)">
          <ons-row>
            <ons-col>
              <header>
                <span class="item-title">{{item.title}}</span>
              </header>
            </ons-col>
          </ons-row>                          
        </ons-list-item>
      </ons-list>
    </ons-page>
  </ons-navigator>

  <ons-template id="detail.html">
    <ons-page ng-controller="DetailController">

      <ons-toolbar>
        <div class="left"><ons-back-button>Back</ons-back-button></div>
        <div class="center">Details</div>
      </ons-toolbar>

      <ons-list modifier="inset" style="margin-top: 10px">
        <ons-list-item class="item">
          <ons-row>
            <ons-col>
              <header>
                <span class="item-title">{{item.title}}</span>
              </header>
            </ons-col>
          </ons-row>
        </ons-list-item>

      </ons-list>

      <ons-list style="margin-top: 10px">
        <ons-list-item class="item">
          <p class="item-desc"><img src="{{item.desc}}" />
<script>
    $(document).ready(function() {
      $("img").panzoom();
    });
</script></p>
        </ons-list-item>
      </ons-list>

      <br>
    </ons-page>
  </ons-template>
</body>  

Solution

  • Any script written in the templates isn't executed. The contents of the template are passed by the navigator as text into DOM object's innerHTML.

    Since eval() isnt done automatically, you'll have to do it manually. refer to this question.

    I suggest you restructure your javascript (put it else where) Then you can use the postPush and prePush properties of ons-navigator to call the function when page loads. refer onsen docs (ons0nvaigator attributes)

    Alternatively, you wan to, you can use ons.ready(callback) in your 'DetailController' controller and perform the panzoom there (if you want to use Angular). refer onsen docs (onsen object ready)