[英]can't bind scope variables in angularjs
我有這些文件:
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'獲取的變量注冊表。 我對依賴注入的整體理解是否良好?
您還需要描述$scope
注入,因為您希望它在控制器函數中可用作第一個參數:
var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController', ['$scope', 'registry', function($scope, registry) { }]);
你沒有正確地注入$ scope
app.controller('PersonController',['$scope', 'registry', function($scope, registry) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.