我想访问我的$范围变量在Chrome的JavaScript控制台。我怎么做呢?

我既不能看到$scope也不能看到我的模块myapp的名称在控制台中作为变量。


当前回答

对于这些答案有一个警告:如果你对控制器进行了别名,那么你的作用域对象将位于scope()返回的对象中的一个对象中。

例如,如果你的控制器指令是这样创建的: <div ng-controller="FormController as frm"> 然后访问控制器的startDate属性,调用angular.element($0).scope().frm.startDate

其他回答

在Chrome的控制台:

 1. Select the **Elements** tab
 2. Select the element of your angular's scope. For instance, click on an element <ui-view>, or <div>, or etc.
 3. Type the command **angular.element($0).scope()** with following variable in the angular's scope

例子

angular.element($0).scope().a
angular.element($0).scope().b

Chrome的控制台

只需将$scope赋值为全局变量。问题解决了。

app.controller('myCtrl', ['$scope', '$http', function($scope, $http) {
    window.$scope = $scope;
}

实际上,我们在开发中比在生产中更需要$scope。

@JasonGoemaat已经提到了,但添加它作为这个问题的合适答案。

我同意最好的是Batarang在选择对象后使用它的$scope(它与angular.element($0).scope()相同,甚至更短的jQuery: $($0).scope()(我的最爱))

同样,如果你像我一样在body元素上有主作用域,那么$('body').scope()就可以了。

为了改进jm的回答……

// 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();

或者如果你使用jQuery,它也会做同样的事情…

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

从控制台访问DOM元素的另一种简单方法(正如jm提到的)是在“elements”选项卡中单击它,它自动被存储为$0。

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

对于这些答案有一个警告:如果你对控制器进行了别名,那么你的作用域对象将位于scope()返回的对象中的一个对象中。

例如,如果你的控制器指令是这样创建的: <div ng-controller="FormController as frm"> 然后访问控制器的startDate属性,调用angular.element($0).scope().frm.startDate