I am a little confused when I am new to Angular. Take the following controller function as an example
function hello($scope) {
$scope.name = '张三'
}
This is a function declaration, $scope should be a formal parameter, right? But changing $scope to another identifier such as s won't work. It can be seen that $scope is the actual parameter passed in when the hello function is called. But these three lines of code are function declarations, so why are actual parameters passed in?
I probably realized that this is not a normal function declaration. Maybe it has something to do with Angular’s controller function binding mechanism? What exactly does it look like?
曾经蜡笔没有小新2017-05-15 16:52:49
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, $injector
the 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
}]);
滿天的星座2017-05-15 16:52:49
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
曾经蜡笔没有小新2017-05-15 16:52:49
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