I'm on my way in learning AngularJS, I'm following a tutorial and I found myself stuck in a point as I cannot make the greetController
controller to work.
Here the HTML:
<!DOCTYPE html>
<html>
<head>
<title>HTML.it</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="userController">
<p>Name: <input type="text" ng-model="user.fname"></p>
<p>Lastname: <input type="text" ng-model="user.lname"></p>
</div>
<div ng-controller="greetController">
<h3>{{greet()}}</h3>
</div>
</div>
</body>
</html>
Here the app.js:
(function(){
var app = angular.module('myApp', []);
app.controller('userController', function($scope){
$scope.user = {fname: "Joe", lname: "Black"};
});
app.controller('greetController', function($scope){
$scope.greet = function () {
return "Hi " + $scope.user.fname + ' ' + $scope.user.lname;
};
});
})();
The result is "{{greet()}}" with no output.
The console says: Cannot read property 'fname' of undefined
I guess I have the user.fname
not readable from the greetController, why is that?
$scope.user user belongs to the controller named 'userController'
Hence it is undefined in the 'greetController'
You may choose $rootScope
to Declare the user as a global object or consider using Service
to share variable among controller.
One simple solution would be using the same userController
.
Using Single Controller Plunker
Using $rootScope Plunker
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments