JoulinRouge JoulinRouge - 1 year ago 46
AngularJS Question

can't bind scope variables in angularjs

I have these files:


<!DOCTYPE html>
<title>Gestore Anagrafica</title>
<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>
Full Name: {{fullName()}} <br>
Is major: {{isMajor()}} <br>
<button ng-click="add()">Add Person</button>
<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>


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

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

this.add = function(person)


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;

The binding does not occur: when i change the name or the age nothing happens, moreover in the beginning the input are all blank but i expect to see 20 in age and testName in firstName. The browser's console shows no error. Am i missing something?

Constraints: the service 'RegistryService' MUST be in another file.

with these two lines

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

i am telling that the module named Person needs something called RegistryService to work, the controller PersonController will use the 'registry' thing located into the RegistryService (hence if i put here something that is not defined into RegistryService is an error). function($scope, registry) is the constructor of the controller that uses a global variable $scope and the variable registry taken from 'RegistryService'. Is my overall understanding of the dependency injection good?

Answer Source

You need to describe $scope injection too, since you expect it to be available in your controller function as the first parameter:

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