angular.js - Angular中控制器函数声明时的$scope到底是形参还是实参?
世界只因有你
世界只因有你 2017-05-15 16:50:49
0
3
771

初学Angular遇到了点困惑,以下面这个控制器函数为例

    function hello($scope) {
        $scope.name = '张三'
    }

这是个函数声明,$scope理应是形参吧?可是把$scope改为其他标识符如s就不行了。可见$scope是hello函数被调用时传入的实参。但这三行代码是函数的声明,怎么就传入实参了呢?

我大概意识到了这不是一个正常的函数声明,可能与Angular的控制器函数的绑定机制有关系?具体是怎样的?

世界只因有你
世界只因有你

reply all(3)
曾经蜡笔没有小新

This kind of obtaining dependencies through parameter passing is a major feature of AngularJS - one of the manifestations of dependency injection.
But why can we get dependencies by just declaring parameters?

AngularJS uses $injector to manage dependent query and loading, such as

// 使用注入器加载应用
var injector = angular.injector(['ng', 'myApp']);
// 通过注入器加载$controller服务
var $controller = injector.get('$controller');
var scope = injector.get('$rootScope').$new();
// 加载控制器并传入一个作用域
var MyController = $controller('MyController', {$scope: scope})

If there is no explicit declaration, $injectorthe dependency relationship is inferred based on the parameter name. At this time, the order of the parameters is meaningless. In other words, we can also declare like this:

angular.module('myApp')
.controller('MyController', ['$scope', 'greeter', function(renamed$scope, renamedGreeter) {
    //do something
}]);
滿天的星座

Well, this thing is just a function declaration where it is written. Whether the name of the formal parameter is important is completely decided by the reader. The ECMAScript standard parser does not think it is important (I guess), but Angular took js and wrote a "js" parser. . . In this way, the name of the function parameter is important

曾经蜡笔没有小新

Scope

The $scope object in AngularJS is used here to convert the domain model
Exposed to views (templates). Just set the property to the scope instance and you can get the value when the template is rendered.

Scopes can also extend data and specific functions for specific views. Just define some functions on the scope instance to convert a specific UI
The logic is exposed to the template.

For example, you can create a getter method for the name variable as follows:

var HelloCtrl = function ($scope) {  
    $scope.getName = function() {     
        return $scope.name;
   };
}

Then use it in the template like this:
<h1>Hello, {{getName()}} !</h1>

$scope
Objects give us very precise control over which parts of the model are within this domain, and which operations are available at the view layer. In theory, AngularJS scopes are very similar to the MVVM pattern ViewModel.

http://note.sdo.com/u/635412003927148913/n/s6cBN~lcIHwG4M1-Y000LW

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!