为什么此代码有效
<div ng-app="my_app" ng-controller="my_ctrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("my_app", []);
function ScopeController($scope) {
$scope.firstName = "John";
$scope.lastName = "Another John";
}
app.controller("my_ctrl", ScopeController);
</script>
而且这不
function ScopeController(scope) {
scope.firstName = "John";
scope.lastName = "Another John";
}
据我了解编程,
$scope
只是ScopeController
的局部变量。而ScopeController
本身只是一个回调函数。那么,为什么我的代码正确工作取决于我如何命名回调的局部变量?如果它不仅是局部变量,为什么还要将其作为参数传递? 最佳答案
没什么意思$scope
只是作用域服务的名称。为了避免踩到您选择的名称,Angular在其大多数内容前都添加了$
前缀,因此您不必为所有冲突的名称添加$
或其他前缀。当您简单地将其称为scope
时,它将停止工作,因为Angular会根据参数的名称确定应注入的服务。而且它不知道任何称为scope
的服务。要使变量名任意,请使用带注释的语法定义您的控制器:
function ScopeController(scope) { ... }
app.controller('my_ctrl', ['$scope', ScopeController]);