Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Angular scope variable to Javascript

I am having a Angular scope variable streetName.

<script type="text/javascript">     angular.module('addApp').controller('add', ['$scope',function($scope) {            $scope.streetName = "Bonita Ln";     }]); </script> 

How can I access streetName in a javascript defined under this controller (add) scope. Please help.

<div ng-app="addApp" ng-controller="add"> StreetName: {{streetName}}  <script type="text/javascript"> //here i need to access the value of streetName... </script>  </div> 
like image 221
JPN Avatar asked Jul 31 '13 02:07

JPN


1 Answers

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

like image 90
Ivan Chernykh Avatar answered Sep 21 '22 17:09

Ivan Chernykh