AngularJs $scope 参数名

AngularJs $scope parameter name

我对 AngularJs 很陌生。在最初的章节中,我看到正在使用 $scope,就像在控制器内部一样。

<script>
var app = angular.module('app1', []);
app.controller('ctrl1', function($scope) {
    $scope.fn = "John";
    $scope.ln = "Parker";
});
</script>

如果我将函数参数 $scope 替换为 $s 左右,那么代码将不起作用。这是为什么?

我的意思是看起来我们正在传递一个回调函数,那么为什么参数名称很重要?

请帮忙

提前致谢
巴鲁

Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events.

$scope是AngularJS提供的对象,是HTML(view)和controller的绑定部分,不能随便改期待。

我建议你阅读 manual

Angular根据需求重新编译代码,做依赖注入。然而,更好的做法是以这种方式编写控制器:

app.controller('testCtrl', ['$scope', function($scope){}]);

即使对文件进行混淆,此代码也能正常工作。 您可以尝试关注 link 以更好地理解这一点。

Understanding dependency injection

您可以重命名 $scope,但您需要添加一些字符串映射(因此 angularjs 将弄清楚如何注入正确的项目)。此功能主要用于缩小:

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

app.controller('ctrl1', ['$scope', function($s) {
    $s.fn = "John";
    $s.ln = "Parker";
}]);

JSFIDDLE.

顺便说一下,最好停止使用 $scope 并开始使用 controlleras 功能。了解它 here

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

app.controller('ctrl1', function() {
    this.fn = "John";
    this.ln = "Parker";
});

<div ng-app="app1" ng-controller="ctrl1 as vm">
   {{vm.fn}}
</div>

JSFIDDLE.