Friday, 31 July 2015

Include script tag on HTML pages in Ionic

In angularjs we can not include the external <script> tag other than the index.html.

So here a  way by which you can include <script>  in your html page in angularjs.

For example -

Following is the code of the main.html page we want to include the <script>:-



<ion-view view-title="News" hide-back-button="true">
    <ion-nav-buttons side="left">
        <button menu-toggle="left" class="button button-icon icon ion-navicon"></button>
    </ion-nav-buttons>
    <ion-content>
        <a class="twitter-timeline" href="https://twitter.com/" >Tweets </a>
<script>
    !function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https';
        if (!d.getElementById(id)) {
        js = d.createElement(s);
        js.id = id;
        js.src = p + "://platform.twitter.com/widgets.js";
        fjs.parentNode.insertBefore(js, fjs);
        }
    }(document, "script", "twitter-wjs");
</script>
    </ion-content>
</ion-view>

which  is not working.

So, what script we want to include on html page, we will include that script in the corresponding controller in the following ways:-

your main.html look like-

<ion-view view-title="News" hide-back-button="true">
    <ion-nav-buttons side="left">
        <button menu-toggle="left" class="button button-icon icon ion-navicon"></button>
    </ion-nav-buttons>
    <ion-content>
        <a class="twitter-timeline" href="https://twitter.com/">Tweets</a>
    </ion-content>
</ion-view>


and your controller.js look like:-


Myapp.controller('MainCtrl', function() {
    !function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https';
        if (!d.getElementById(id)) {
        js = d.createElement(s);
        js.id = id;
        js.src = p + "://platform.twitter.com/widgets.js";
        fjs.parentNode.insertBefore(js, fjs);
        }
    }(document, "script", "twitter-wjs");
})
 Now it will be work.


No comments:

Post a Comment