During my journey of learning AngularJS, I decided to create a small app that would allow data to be passed between two controllers using services. Below is the code snippet that showcases how I achieved this:
The Controller Code
<!DOCTYPE html>
<html lang="en-us" ng-app="myApp">
<head>
<title></title>
<script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.service('sampleService', [function () {
this.user = {name: 'pra', empno: '1234'};
this.designation = 'teamlead';
}])
app.controller('NameCtrl', ['$scope','$sampleService', function ($scope,$sampleService) {
$scope.empname = $sampleService.user.name;
$scope.empnumber = $sampleService.user.empno;
$scope.empdesignation = $sampleService.designation;
$scope.changevals = function(){
$sampleService.user.empno = '9876';
$sampleService.designation = 'manager';
$scope.empnumber = $sampleService.user.empno;
$scope.empdesignation = $sampleService.designation; }
}])
app.controller('NameCtrl1', ['$scope','$sampleService', function ($scope) {
$scope.uEmpiId = $sampleService.user.empno;
$scope.uempdesignation = $sampleService.designation;
$scope.updatevals = function(){
$scope.uEmpId = $sampleService.user.empno;
$scope.uempdesignation = $sampleService.designation; }
}])
</script>
</head>
Here is my HTML code snippet
<body>
<div ng-controller="NameCtrl">
<div><b> Details - Controller 1</b></div>
<p>Name : {{empname}}</p>
<p>Location : {{empnumber}}</p>
<p>Designation : {{empdesignation}}</p>
<input type="button" value="Change Values" ng-click="changevals()" />
</div>
<br />
<div ng-controller="NameCtrl1">
<div><b>Details - Controller 2</b></div>
<input type="button" value="Change Values" ng-click="updatevals()" />
<p>Location : {{uEmpiId}}</p>
<p>Designation : {{uempdesignation}}</p>
</div>
</body>
I am currently facing an issue with displaying the details and encountering an error message like this:
angular.js:13920 Error: [$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=%24sampleServiceProvider%20%3C-%20%24sampleService%20%3C-%20NameCtrl at Error (native)
If anyone can provide guidance on where I might be going wrong with the code, I would greatly appreciate it.
Thank you in advance for your help.