Encountering an issue when transferring data between controllers utilizing a demo service

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.

Answer №1

Avoid using '$' when injecting a service into your controller:

Replace:

app.controller('NameCtrl', ['$scope','$sampleService', function ($scope,$sampleService) {

with:

app.controller('NameCtrl', ['$scope','sampleService', function ($scope,sampleService) {

UPDATE

Additionally (per @estus recommendation), the service is undefined in NameCtrl1

Update the code for your NameCtrl2 from

app.controller('NameCtrl1', ['$scope','$sampleService', function ($scope) {

to

app.controller('NameCtrl1', ['$scope','sampleService', function ($scope, sampleService) {

In your code, whenever you use the sampleService, avoid using sampleService instead of $sampleService.


UPDATE 2

Revise your

app.service('sampleService', [function () {
  this.user = [name = 'pra', empno ='1234']
  this.designation = 'teamlead';
}])

to

app.service('sampleService', [function() {
              this.user = {name : 'pra', empno : '1234'};
              this.designation = 'teamlead';
          }])

The final code would appear as follows:

<!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, sampleService) {
              $scope.uEmpiId = sampleService.user.empno;
              $scope.uempdesignation = sampleService.designation;
              $scope.updatevals = function() {
                  $scope.uEmpiId = sampleService.user.empno;
                  $scope.uempdesignation = sampleService.designation;
              }
          }])
      </script>
  </head>
  <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>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Glyphicon icon fails to appear on the initial page load and only shows up after refreshing the

I have been utilizing bootstrap.min.css from bootstrap v3.3.5 which I downloaded from http://getbootstrap.com and used it locally. However, I encountered an issue with glyphicons when running it on IE 9 and above. The glyphicon icon disappears on the first ...

altering the URL of an AngularJS application prior to its initial load

I have encountered an issue with the Instagram API where the result redirects to my app but Instagram does not accept URLs that include the "#" symbol. For example, http://localhost:3000/#/functionalists is not being accepted due to the "/#/". My app use ...

"Troubleshooting CSS styling in React material-ui when using withStyles from an external

After reviewing this specific question, I still couldn't figure out how to make it work. The main goal is to keep the styles separate from the component file for a more organized setup. Everything runs smoothly without incorporating a theme. I atte ...

Adjust text size using the "increase toggle"

I'm having trouble adjusting the font size of my text within the <div class="comment more>. Whenever I try to wrap the text in a <p>, the "more toggle" functionality stops working properly. Instead of revealing more text when I click on "m ...

Tips for dividing by a large number

I am currently attempting the following: const numerator = 268435456; const denominator = 2 ** 64; const decimalFraction = numerator / denominator; In order to achieve this, I have experimented with utilizing the code provided in this link: : const rawVal ...

Differentiating between an individual array and an array containing multiple arrays

Can jQuery differentiate between a regular array, an array of arrays, and an array of objects? var a = [1,2,3]; var a2 = [[12,'Smith',1],[13,'Jones',2]]; var a3 = [{val:'12', des:'Smith', num:1}]; //a = regular arr ...

I recently installed bootstrap, jquery, and popper.js on my live server, but to my surprise, nothing was appearing on the screen. Despite compiling the

After successfully installing bootstrap, jquery, and popper.js, I encountered an issue on my live server where nothing was displaying. Oddly enough, no errors were detected after compiling the code. import { createApp } from 'vue' import App from ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

An error occurred: Cannot access the 'splice' property of an undefined value

//Screenshot <div v-for='(place) in query.visitPlaces' :key="place.name"> <div class="column is-4 is-narrow"> <b-field label="Nights"> <b-input type="text" v-model="place.nights" placeho ...

How can I display a spinner/loader gif when the page loads using Vue?

When it comes to loading components on a webpage, jquery has the options of $( document ).ready() and onload. But in Vue, how can we achieve the same effect? For example, when a user clicks our page, how can we display a spinner until all contents are load ...

Unresolved styles in React component linked to styles.css file

As I dive into creating a registration page in ReactJS, I encounter a frustrating issue with my styles not applying correctly from the styles.css file. Let's take a look at my RegisterPage.jsx component: export default function RegisterPage() { ret ...

What is the best way to include keys in my JSON data, rather than just values?

I've encountered an issue with the PrimeVue datatable I created, as it is only showing empty rows. After investigating, I believe the problem lies in my JSON data structure, where the fields do not have keys. What modifications should be made to stan ...

How can I manage the asynchronicity of Hapi.js, fs.readFile, fs.writeFile, and childProcess.exec?

My code execution seems to be resulting in an empty list, could it be that my asynchronous calls are incorrect? I've tried rearranging and breaking things into functions but there still seems to be a timing issue with my execution. The order in which ...

Is it possible to use a webcam to scan a QR code directly into a webpage?

Is it possible to enable users to input data on a webpage using QR code scanning? I'm unsure if there is a tool that can be integrated into the page or paired with a library to make this happen, or if I need to consider an external solution beyond th ...

Creating a minigame using JQuery (Javascript)

I am currently developing a collection of mini-games for my big project. The approach I've taken in creating this mini-game is similar to one I used previously. However, unlike my previous version which only had one PuzzleContainer, this new iteration ...

Trouble is arising in rendering events with years before 100 (specifically years 0000 - 0099) when using the ISO8601 format in fullCalendar

I've created a Calendar that showcases various events using fullcalendar. The events span from the years 0001 to 6000. Fullcalendar requires dates in ISO8601 format, and I am providing them as such. Events from the years 0100-6000 render perfectly w ...

AngularJS restructured the homepage to function as a shell page instead of the traditional index page

As a newcomer to angularJS, I am learning that it is typically designed for Single Page Applications. Most example logins I come across define the index.html as the main page, with the ng-view portion contained within. However, in my situation, the Login ...

The MaskedInput text does not appear properly when it is passed through the props

Currently, I am facing an issue with a Material UI OutlinedInput along with the MaskedInput component from react-text-mask. Everything works fine when I input text initially and the element is not in focus. However, upon closing and reopening the Dialog wi ...

What steps do I need to take to execute a script that utilizes the mootools library within an asp.net environment

I've been working on a website that includes a mail form. I'm using the Mootools 1.4.3 library along with FormCheck 1.6.js. However, when I click the button, nothing happens except for the page refreshing. I really like this form and want to make ...

Hold off until the script is successfully downloaded and executed, then patiently wait for the DOM to finish loading

I'm facing a challenge with running Javascript conditionally without it being in requirejs form. The script is located on the same server/domain as the requesting page, where an ajax call needs to be made. Is there a foolproof way to ensure that an a ...