Search code examples
javascriptangularjsangularjs-scope

Angular: Access scope from within <script> tag


I have a scope variable that is being populated from my API. I can access this from HTML with the {{}} braces.

I need to pass the scope into a script file.

<script type="text/javascript"> var data = {{data}}  </script>

From what i've seen so far it seems overly complex for something relatively simple.

What is the recommended way of doing this? Isn't this quite a common problem?

Specifically, im trying to use a javascript graphical library Cytoscape.js. The graph is populated from a javascript object. I'd like to populate this javascript object from the scope. I found this:

Pass Angular scope variable to Javascript

I'm wondering whether generally this is handled in a different way in angular as it seems like a hack.


Solution

  • First of all to be clear, the Angular does not perform interpolation within script tags.

    https://docs.angularjs.org/guide/interpolation

    There are some ways around this... calling directly the value of the variable can be one of the ways:

    <body ng-app="myApp">
        <div ng-controller="myController" id="yourControllerElementID">
    
        </div>
    </body>
    
    <script type="text/javascript">
        var app = angular.module("myApp", []);
    
        app.controller("myController", myController);
    
        function myController($scope){
            $scope.data = 'some value';
        }
    
        // Capturing value from outside the controller
        setTimeout(function(){
            var data = angular.element(document.getElementById('yourControllerElementID')).scope().data;
        }, 1000);
    </script>
    

    Otherwise using interpolation as you wanted , would create a hidden input with the value of the controller and capture this value with vanilla javascript or jquery:

    <body ng-app="myApp">
        <div ng-controller="myController">
            <input type="hidden" id="myValueFromController" value="{{data}}" />
        </div>
    </body>
    
    <script type="text/javascript">
        var app = angular.module("myApp", []);
    
        app.controller("myController", myController);
    
        function myController($scope){
            $scope.data = 'some value';
        }
    
        // Capturing value from outside the controller
        setTimeout(function(){
            var data = document.getElementById("myValueFromController").value;  // or
            var data = $("#myValueFromController").val();
        }, 1000); 
    </script>
    

    Anyway let's say it would not be the Angular Way to work , but as I do not know what the scope of its development, this is the best I can tell you.