我有这些文件:
的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;
};
}]);
绑定不会发生:当我更改名称或年龄没有任何反应时,此外在开头输入都是空白但我希望在firstName中看到20和testName中的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'获取的变量注册表。我对依赖注入的整体理解是否良好?
答案 0 :(得分:2)
您也需要描述$scope
注入,因为您希望它在控制器函数中可用作第一个参数:
var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController', ['$scope', 'registry', function($scope, registry) { }]);
答案 1 :(得分:1)
你没有正确地注入$ scope
app.controller('PersonController',['$scope', 'registry', function($scope, registry) {