angularjs - I'm trying to access angular variable through JavaScript. But Its not working -


i'm using :

window.onload=function(){     var dom_el2 = document.queryselector('[ng-controller="myctrl"]');     var ng_el2 = angular.element(dom_el2);     var ng_el_scope2 = ng_el2.scope();     console.log(ng_el_scope2);     var datan3 = ng_el_scope2.itson;     console.log(datan3);       } 

it showing value of itson undefined everytime. i've tried method. please suggest method access angular variable javascript except using $window.

i totally agree @mikemccaughan, it's bad practice ! if need it, here simple example controller , vanilla js access variables , functions outside

index.html

<!doctype html>  <html lang="en" ng-app="app"> <head>   <meta charset="utf-8">   <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>   <script src="script.js"></script> </head>  <body>     <div id="mycontroller" ng-controller="mycontroller vm">         name {{vm.fullname}}     </div>     <br>     <button onclick="accesscontrollerscopevar()">get full name</button>       <button onclick="accesscontrollerscopefunction()">say hello !</button>    </body> </html> 

script.js

angular.module('app', []);  angular .module('app') .controller('mycontroller', ['$scope', function ($scope) {      var vm = this;      vm.fullname = 'marty mcfly';      vm.getfullname = function() {         return vm.fullname;     }  }]);  function accesscontrollerscopevar() {     var scope = getscopefor("mycontroller");     scope.$apply(function () {         alert(scope.vm.fullname);     }); }  function accesscontrollerscopefunction() {     var scope = getscopefor("mycontroller");     scope.$apply(function () {         alert('hello ' + scope.vm.getfullname());     }); }  function getscopefor(id) {     var el = document.getelementbyid(id);     var scope = angular.element(el).scope();     return scope; } 

here plunker : https://plnkr.co/edit/7u78a6xdlaef2qogwucc?p=preview

alternative

if don't wan't use ids, here sample using document.queryselector :

https://plnkr.co/edit/ataojhu9zuhyzlc5us5y?p=preview


Comments