我有这些文件:

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Gestore Anagrafica</title>
</head>
<body>
    <div>
        <h3>Insert new person</h3>
        <div ng-app="Person" ng-controller="PersonController">
            First Name: <input type="text" ng-model="firstName"><br>
            Last Name: <input type="text" ng-model="lastName"><br>
            Age: <input type="number" ng-model="age"><br>
            <br>
            Full Name: {{fullName()}} <br>
            Is major: {{isMajor()}} <br>
            <button ng-click="add()">Add Person</button>
        </div>
    </div>
    <script type="text/javascript" src="js/angular.js"></script>
    <script type="text/javascript" src="js/RegistryService.js"></script>
    <script type="text/javascript" src="js/PersonController.js"></script>
</body>
</html>


js / RegistryService.js:

angular.module('RegistryService', []).

service('registry', function()
{
    this.people = [];

    this.add = function(person)
    {
        people.push(person);
    }
});


js / PersonController.js:

var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController',['registry', function($scope, registry) {
    $scope.firstName = "testName";
    $scope.lastName = "";
    $scope.age = 20;

    $scope.isMajor = function()
    {
        return $scope.age > 18;
    };

    $scope.add = function()
    {
        registry.add({  'firstName': $scope.firstName,
                        'lastName': $scope.lastName,
                        'age': $scope.age});

    };

    $scope.fullName = function()
    {
        return $scope.firstName + " " + $scope.lastName;
    };
}]);


绑定不会发生:当我更改名称或年龄时,什么也没有发生,此外,在开始时输入均为空白,但我希望看到20岁,而firstName中的testName。浏览器的控制台未显示任何错误。我想念什么吗?

约束:服务“ RegistryService”必须位于另一个文件中。

题:
这两行

var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController',['registry', function($scope, registry) {


我告诉名为Person的模块需要一个名为RegistryService的东西才能工作,控制器PersonController将使用位于RegistryService中的“注册表”东西(因此,如果我在此处放入未定义到RegistryService中的东西,则会出现错误)。 function($ scope,Registry)是使用全局变量$ scope和变量注册表的控制器的构造函数,该变量注册表取自'RegistryService'。我对依赖项注入的整体理解是否很好?

最佳答案

您还需要描述$scope注入,因为您希望它在控制器功能中作为第一个参数可用:

var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController', ['$scope', 'registry', function($scope, registry) { }]);

10-07 15:18