angular js 中 $scope 的可变范围如何工作?

How variable scope of $scope in angular js works?

我是 angular JS 的初学者,我在教程中找到了这段代码。

var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', function($scope) {
  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.'},
    {'name': 'Motorola XOOM™ with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.'},
    {'name': 'MOTOROLA XOOM™',
     'snippet': 'The Next, Next Generation tablet.'}
  ];
});

此代码运行良好,但我想知道 $scope 的变量范围是如何工作的。从代码来看,$scope 似乎是一个局部变量,它的范围仅限于函数。

那为什么我不能更改 $scope 变量的名称?如果我更改函数内所有出现的变量名,它似乎不起作用

angular 中以 $ 开头的所有内容都是这里的服务范围也是将视图与控制器绑定并允许您使用 双向绑定 的服务。

是的,$scope 仅限于一个特定的组件,我们可以说指令或 controller.But 我们还有父亲的范围 $rootScope。

因此您可以将 $rootScope 用作全局内容的服务。

希望它能消除您的疑虑。

以下是一些有用的链接:-

Github(最佳资源)

Doc

来自 AngularJS 文档:

Scope is the glue between application controller and the view... Both controllers and directives have reference to the scope, but not to each other.

$scope 由 angular 创建并通过引用注入(依赖注入)到您的控制器函数中。

想一想这个简单的 javascript 示例,然后将您的想法扩展到 AngularJS

(function() {
     // var myscope is not global. it's in the closure
     // of my anonymous function
     var myscope = {
        "samplekey" : "samplevalue"
     }

     // .... You can do anything with scope

     // Imagine this function as your controller
     function myController($scope) {
        // Here I can work with $scope variable
        $scope.data = { "anotherkey" : "anothervalue" };
        console.log($scope.samplekey); // It works fine
     }

     // inject myscope into the controller function
     myController(myscope);

     // I can access the new property added to myscope variable
     // by the controller function (maybe I can use it in a view).  
     console.log(myscope.data.anotherkey); // anothervalue 

}());

您也可以在 AngularJS 中使用您想要的任何变量作为范围。但是您必须指定您创建的变量引用范围变量。

phonecatApp.controller('PhoneListCtrl',['$scope', function(varAsScope) {
  varAsScope.phones = [
    {'name': 'Nexus S', 'snippet': 'Fast just got faster with Nexus S.'},
    {'name': 'Motorola XOOM™ with Wi-Fi', 'snippet': 'The Next, Next Generation tablet.'},
    {'name': 'MOTOROLA XOOM™', 'snippet': 'The Next, Next Generation tablet.'}
  ];
}]);

这里是Working Example

Angular 使用依赖注入。 $scope 是一个注入值。它本质上是一个对象,包含该模块的相关控制器内的所有 ng- 引用。

"A module is a collection of services, directives, controllers, filters, and configuration information." -angular source

当您访问模块包含的集合中的某些内容时,会注入该访问的范围。例如创建模块时,模块创建控制器属性

/**
* @ngdoc method
* @name angular.Module#controller
* @module ng
* @param {string|Object} name Controller name, or an object map of controllers where the
 *    keys are the names and the values are the constructors.
 * @param {Function} constructor Controller constructor function.
 * @description
 * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
 */
 controller: invokeLater('$controllerProvider', 'register'),

此 属性 已注册到 controllerProvider。

The controller is injectable (and supports bracket notation) with the following >locals:
*
* * $scope - Current scope associated with the element

所以当你使用这个代码时

phonecatApp.controller('PhoneListCtrl', function($scope){

您正在做的是从控制器提供程序访问 'PhoneListCtrl 控制器,然后调用所提供的函数,并使用存储在该模块的 PhoneListCtrl 中的关联范围进行调用。

关于变量名 $scope,angular 可以判断您是否正在使用此 "keyword" 的原因是通过正则表达式过程。如果你在一个函数上使用 .toString() ,它会将整个东西转换成一个字符串,然后你可以解析它以查看函数中的内容。 Angular 这样做,

"The simplest form is to extract the dependencies from the arguments of the function. This is done by converting the function into a string using toString() method and extracting the argument names."

正则表达式在 angular 中定义为 var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; 您可以在 https://regex101.com/r/qL4gM8/1

中使用它进行测试

这就是 Angular 知道您在函数参数中使用了变量 $scope 的方式。