mediaguru
mediaguru

Reputation: 1917

Pass AngularJS variable to script tag in html view

Here's the issue. I have a 3rd party script which needs to be embedded on my AngularJS app, in the html as a <script> tag. I need to pass scope variables to this script (name, email etc). My first attempt here is to figure out if I can pass a scope variable from the controller to a script tag on page load. Perhaps there's a better approach, like making the script a template, but I'm not sure. I'm worried that if I succeed in this basic concept, that the script tag will render the real data before the variable is passed.

Here's the HTML:

  <body>
    <div ng-controller="MainCtrl">
        Angular variable: {{foo}}
    </div>
  </body>
  <script type="text/javascript">
    console.log(foo); // $scope.foo?
  </script>

Here's the controller:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
      $scope.foo = 'bar';
})

Plunker: https://plnkr.co/edit/5rcnqUxHRHMthHmkwVuZ?p=preview

Upvotes: 1

Views: 2352

Answers (1)

Krzysztof Raciniewski
Krzysztof Raciniewski

Reputation: 4924

If you want to embed third party script(jQuery plugin or something else) to your AngularJS application you should write wrapper to this script(simple directive or component)

The way you presented will not work - I guarantee

I found a simple example for you how to create AngularJS directive and wrap some simple jquery plugin:

<html>
<head>
    <title>AngularJS wrapp jquery plugin</title>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="https://raw.github.com/SamWM/jQuery-Plugins/master/numeric/jquery.numeric.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>

    <script type="text/javascript">
        var app = angular.module('myApp', []);
        app.directive('numberMask', function() {
            return {
                restrict: 'A',
                link: function(scope, element, attrs) {
                    $(element).numeric();
                }
            }
        });
    </script>
</head>

<body>
    <div ng-app="myApp">
        <div>
            <input type="text" min="0" max="99" number-mask="" ng-model="message"> 
        </div>
    </div>

</body>

Upvotes: 1

Related Questions