Search This Blog

Tuesday, April 24, 2018

Embed dynamic JavaScript in angular page using controller injection

To insert a widget, lets take trading view widget if you want to insert javascript widget which needs to  be loaded on a page, you need to inject it inside the html page.

It won’t load if you are inserting the script directly in the html page.

You need to insert it via controller.


look at the controller code

app.controller('ChartsController',function($scope){

$scope.init = function(){

console.log("called on scope init");

$(' <div class="tradingview-widget-copyright"><a href="https://www.tradingview.com/symbols/NSE-ICICIBANK/" rel="noopener" target="_blank"><span class="blue-text">ICICIBANK</span> <span class="blue-text">chart</span> by TradingView</a></div> <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script> <script type="text/javascript"> new TradingView.widget( { "autosize": true, "symbol": "NSE:ICICIBANK", "interval": "D", "timezone": "Asia/Kolkata", "theme": "Light", "style": "8", "locale": "en", "toolbar_bg": "#f1f3f6", "enable_publishing": false, "withdateranges": true, "hide_side_toolbar": false, "allow_symbol_change": true, "watchlist": [ "NSE:RNAM", "NSE:LUPIN" ], "details": true, "hotlist": true, "calendar": true, "news": [ "stocktwits", "headlines" ], "studies": [ "IchimokuCloud@tv-basicstudies", "BB@tv-basicstudies", "RSI@tv-basicstudies", "Volume@tv-basicstudies" ], "container_id": "tradingview_7e6c5"} ); </script>').appendTo('#tradingview_7e6c5');

}

});



Add a route in the router section of the app.js

when('/charts', {

templateUrl: 'views/charts.html',

controller: 'ChartsController'

}).


Add this  to the chart.html


<div ng-init="init()" class="tradingview-widget-container">

<div id="tradingview_7e6c5"></div>

<div class="tradingview-widget-copyright"><a href="https://www.tradingview.com/symbols/NSE-ICICIBANK/" rel="noopener" target="_blank"><span class="blue-text">ICICIBANK</span> <span class="blue-text">chart</span> by TradingView</a></div>

</div>

You can embed javascript widgets from trading view like this.

No comments:

Post a Comment