How do I access the $scope variable in browser's console using AngularJS?

前端 未结 19 1539
渐次进展
渐次进展 2020-11-22 08:35

I would like to access my $scope variable in Chrome\'s JavaScript console. How do I do that?

I can neither see $scope nor the name of my mo

19条回答
  •  时光取名叫无心
    2020-11-22 08:52

    To improve on jm's answer...

    // Access whole scope
    angular.element(myDomElement).scope();
    
    // Access and change variable in scope
    angular.element(myDomElement).scope().myVar = 5;
    angular.element(myDomElement).scope().myArray.push(newItem);
    
    // Update page to reflect changed variables
    angular.element(myDomElement).scope().$apply();
    

    Or if you're using jQuery, this does the same thing...

    $('#elementId').scope();
    $('#elementId').scope().$apply();
    

    Another easy way to access a DOM element from the console (as jm mentioned) is to click on it in the 'elements' tab, and it automatically gets stored as $0.

    angular.element($0).scope();
    

提交回复
热议问题