Pass Angular scope variable to Javascript

后端 未结 4 1708
醉话见心
醉话见心 2020-11-27 03:20

I am having a Angular scope variable streetName.



        
相关标签:
4条回答
  • 2020-11-27 03:49

    This way is long but it works:

        angular.element(document.querySelector('[ng-controller="add"]')).scope().streetName
    

    More readable:

        var dom_el = document.querySelector('[ng-controller="add"]');
        var ng_el = angular.element(dom_el);
        var ng_el_scope = ng_el.scope();
        var street_name = ng_el_scope.streetName;
    

    And it's much shorter if you're using jQuery:

        var street_name = $('[ng-controller="add"]').scope().streetName;
    

    Link to jsfiddle demo

    0 讨论(0)
  • 2020-11-27 03:51

    You may pass your scope vat to common js var with $window service.

    Like this:

    angular.module('addApp', [])
    .controller('add', ['$window', function ($window) {
        ...
        $window.streetName = $scope.streetName; 
        ...
    }
    

    and attach your js after that in comon js code like that:

    <script type="text/javascript">
        document.write("\<script src='...' type='text/javascript'>\<\/script>");
    </script>
    

    But keep in mind that it's workaround, not best solution

    0 讨论(0)
  • 2020-11-27 03:55

    I faced a similar problem. I found a work around. It worked well for me but not sure if it is the right approach.

    Create a hidden input field in the html and assign it your value from angular. Access this value in javascript. Make sure you create it before your script tag so that it will be initialized when you reach your script tag.

    Something like this:

    <div ng-app="addApp" ng-controller="add">
        StreetName: {{streetName}}
        <input type="hidden" id="dummyStreetName" value={{streetName}}>
        <script type="text/javascript">
            console.log("I got the street name "+$("#dummyStreetName").val());
        </script>
    </div>
    
    0 讨论(0)
  • 2020-11-27 04:05

    Simple, non-complicated, jQuery solution:

    HTML

    <div id="data" data-street="{{streetName}}"></div>
    

    Javascript

    $(document).ready(function() {
        var streetName = $('#data').data('street');
    });  
    

    The $(document).ready... is important to give angular time to set the variables.

    0 讨论(0)
提交回复
热议问题