Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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>
share|improve this question
up vote 20 down vote accepted

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

share|improve this answer
    
But this is returning null. It couldnt read the controller 'add'. – JPN Jul 31 '13 at 11:24
    
@JPN Seems like the element is not ready yet. Try to put my code in window.onload handler – Cherniv Jul 31 '13 at 11:26
    
Its working :) but sometimes it gives null. Looking at what I am missing.. thanks a ton..!! – JPN Jul 31 '13 at 11:34
    
@JPN in case of null you can add some little setInterval that will check for element/scope until it is completely ready. Good luck! – Cherniv Jul 31 '13 at 11:38
    
@chrmiv I found out the issue... I didnt include the ng-controller in the div tag which wraps around the javascript tag.. now its perfectly working. thank you so much.. – JPN Jul 31 '13 at 12:38

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

share|improve this answer
    
thanks for the tip! – Sunny Jun 9 '14 at 12:26
    
This is perfect! Just in case it's not clear, you can access values assigned to the angular $window object with the javascript window object. – Dr. C. Hilarius Sep 10 '14 at 1:31
3  
@Sergey Panfilov : but how can i access that value in myscript value.? – lalitpatadiya Jul 2 '15 at 7:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.