Having trouble with the functionality of the AngularJS Custom Service?

I have developed a straightforward service as shown below:

var app = angular.module('myApp', ['ngRoute']);
app.service('UserService', function() {

this.user = {firstName:"",middleName:"",lastName:"",email:"",dob:""};
this.addUser = function (user) {
  users.push(user);
}
this.displayUser = function (user) {
  this.user = user;
}
});

Below is the controller where I intend to make use of the service:

app.controller('DisplayUserController', ['$scope','UserService', 
function($scope, UserService) {

$scope.user = UserService.user;

}]);

This snippet showcases the HTML section where I am passing the user object to user directive:

<div ng-controller="DisplayUserController">
 <div>{{user.firstName}}</div>
 <div>{{user.middleName}}</div>
 <div>{{user.lastName}}</div>
</div>

Any idea why I keep encountering the "Unknown provider: userProvider <- user" error? Assistance would be greatly appreciated.

Answer №1

Make sure to link the ngModel with your custom directive:

.directive('userInfo', function() {
  return {
    restrict: 'E',
    scope:{
      'userDetails': '=ngModel'
    },
    templateUrl:'display-user-details.html',
    controller: function($scope) {
        var userDetails = $scope.userDetails;
        $scope.firstName = userDetails.firstName;
        $scope.lastName = userDetails.lastName;
        $scope.email = userDetails.email;
        $scope.phoneNumber = userDetails.phoneNumber;
        $scope.address = userDetails.address;
    }
  };
});

Answer №2

When faced with an issue in my directive, I realized that incorporating the UserService as a dependency resolved the problem. However, I am uncertain whether this is considered best practice.

angular.module('myApp').directive('user', ['UserService', function() {
  return {
     restrict: 'E',
     templateUrl:'templates/display-single-user.html',
     controller: function($scope, UserService) {

         $scope.firstName = UserService.user.firstName;
         $scope.middleName = UserService.user.middleName;
         $scope.lastName = UserService.user.lastName;
         $scope.email = UserService.user.email;
         $scope.dob = UserService.user.dob;
     }
  };
}]);

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 POST request functions flawlessly on the local server, but encounters issues once deployed to Google Cloud Platform

Even though the Axios post request works fine on my local server, it throws a 404 not found error after I deploy the project on Google Cloud. On localhost, all requests are directed to URLs starting with http://localhost:9000/api/..., handling post reques ...

Validating Cognito credentials on the server-side using Node.js

I am currently developing server-side login code for AWS Cognito. My main goal is to verify the existence of a user logging into the identity pool and retrieve the attributes associated with them. With email login, everything is running smoothly using the ...

Error: The function callback.apply is not a valid function (Node.js and Mongodb)

Encountered an error when adding the line "{ upsert: true }": Error message: TypeError: callback.apply is not a function // Accessing routes that end in /users/competitorAnalysisTextData // ---------------------------------------------------- router . ...

Challenges encountered while using Selenium WebDriver to upload images

I'm having trouble adding an image as a normal attachment to an email (not as an inline image). When inspecting the HTML DOM with Firebug, I noticed there are two elements with xpath //input@type='file', which is due to the presence of two b ...

serving index.html using express and react

I am currently working on an application with Express, which includes a create-react-app. My goal is to display the index.html file located in the public folder of the create-react-app when a user visits the root URL. Below is the code snippet from my inde ...

What is the process for incorporating Web Assembly scripts into a React Native application?

I find myself wondering if this task is even feasible. If it is doable, I suspect we'll have to utilize WebViews, but maybe I'm just being overly analytical. Attempted to research this topic, but unfortunately, came up empty-handed. ...

How to Set Up Bower in WebStorm

I require assistance with the installation process of bower in WebStorm. My current version is 11.0.2 and I have a package.json file that needs to include bower.json for implementing a date-picker in Angular.js. To achieve this, I need to install bower. Th ...

Why is there an issue with the JavaScript array when accessing data['sax']?

There seems to be some confusion regarding the contents of this array and how it assigns values to the variable set. It would be greatly appreciated if someone could provide an example pertaining to the usage of data['sax']. Additionally, an expl ...

Discovering the summation of chosen options multiplied by input fields with the assistance of jQuery

I am attempting to calculate the average for different subjects and print it immediately whenever the user modifies a value. To input the marks, I am using input fields and corresponding select options for the hours allotted to each subject. I can accura ...

In the Opera browser, the closing script tags seem to mysteriously vanish

I recently built a website using bootstrap and implemented the JQuery load function to merge separate HTML files into one for better organization. The site is currently live on github pages. However, I've encountered an issue specifically with Opera ...

Having issues with ToggleClass and RemoveClass functionalities not functioning properly

As a novice in Jquery and CSS/scss, I've managed to create dynamic bootstrap cards for recording players. Each card consists of a music-container with control-play and vinyl elements. I aim to have multiple bootstrap cards generated based on the data ...

Mastering Data Labels in ng2-chart: A step-by-step guide

Once again, I find myself battling my Angular and JavaScript challenges, each question making me feel a little less intelligent. Let me walk you through how I got here. In my most recent project, I wanted to enhance the user experience by incorporating sl ...

Is the form validation failing to update after an item is removed from the model? Possible bug detected?

Lately, I've been exploring AngularJS and encountered an interesting bug. Let me start by sharing some functional code: View: <body ng-controller="MainCtrl"> <form name="form"> <div ng-repeat="phone in phoneNumbers"> ...

In AngularJS, the input fields are dynamically updated only after the submit button is clicked

When typing in the input fields, the badge field should not update directly. The fields will only populate after pressing the Submit button. //main.html <!DOCTYPE html> <html lang="en" ng-app="MyApp"> <head> <meta charset="UTF-8& ...

Exploring Selenium: Techniques for examining the source code of an unidentified function

I'm fairly new to using Selenium. I have come across this javascript code snippet and I am attempting to use Selenium to inspect the script, but I haven't had much luck so far. My main goal is to employ Selenium to access/inspect the script in or ...

Implementing the loading of a Struts 2 action with jquery in javascript

Looking to refresh a specific div using JavaScript with jQuery to target the div and a Struts action that loads the content. Can anyone offer advice on how to achieve this? The challenge lies in utilizing JavaScript and jQuery for this task. Best regards ...

I can see the JSON data printing to the console in Ionic 3, but it doesn't display on

I seem to be facing a challenge with passing the 'item' to my search function in my Ionic 3 app. Although I was able to successfully connect to a json data file and print objects to the console, I am encountering an error message on the page that ...

Can I update a label using ajax from the controller?

Hello everyone, I am facing a challenge in changing the text label coming from my Controller's JsonResult. There are two specific issues that I am encountering: 1) I am having difficulty displaying the text sent from my controller onto my view... ...

Error! D3.js is throwing an Uncaught TypeError because it cannot find the function .enter(...).append(...).merge

Currently, I am facing an issue while attempting to construct a table with multiple nested dropdowns using d3.js. The problem arises when switching from a newer version of d3 where my code functions flawlessly to d3.js v3. Upon replacing the newer version ...

Dealing with ng-repeat in Angular can be challenging when working with JSON data

Apologies if this question has been asked before, I tried searching but couldn't find an answer. Issue: When calling a web service, I am getting poorly formed JSON data from a Dynamics Nav service: JSON: "[{\"type\":\"2\",&bsol ...