Implementing directives in controllers: A step-by-step guide

Can someone help me understand how to inject a custom directive into a controller and call the functions show() and hide()? I keep getting the following error:

Error: [$injector:unpr] Unknown provider: inputThrobberProvider <- inputThrobber <- landingCtrl

Here is the example code:

var app = angular.module('myapp', ['ngAnimate', 'ui.router', 'templates']);

app.directive('inputThrobber', [function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      controller: function($scope, $element) {
        var inputThrobberCtrl = {
          show: function() {
            $element.addClass('throbbing');
          },
          hide: function() {
            $element.removeClass('throbbing');
          }
        };

        return inputThrobberCtrl;
      }
    };
  }])
  .controller('landingCtrl', ['$scope', 'geolocation', 'inputThrobber', function($scope, geolocation, inputThrobber) {

    // inputThrobber.show()
    geolocation.getAddress().then(function(address) {
        $scope.address = address;
      }).catch(function(err) {
        $scope.error = error;
        $scope.address = '';
      })
      .finally(function() {
        // $inputThrobber.hide()
      });

  }]);

Answer №1

Below is a snippet showcasing how to trigger an event to display/hide a loading spinner:

app.directive('inputSpinner', [function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      controller: function($scope, $element) {
        $scope.$on('startSpinning', function() {
          $element.addClass('spinning');
        });
        $scope.$on('stopSpinning', function() {
          $element.removeClass('spinning');
        });
      }
    };
  }])

.controller('homeCtrl', ['$scope', 'geolocation', function($scope, geolocation) {
    $scope.$broadcast('startSpinning');
    geolocation.getAddress().then(function(address) {
        $scope.address = address;
      }).catch(function(err) {
        $scope.error = error;
        $scope.address = '';
      })
      .finally(function() {
        $scope.$broadcast('stopSpinning');
      });
}]);

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

onpageshow event behaves as expected exclusively on webkit browsers (triggers function solely when visible on the screen)

I am inserting an HTML file using an object tag. The encompassing div of the object tag is hidden with a display:none property. However, I encounter an issue where the onpageshow event that I placed on the body tag of the HTML object behaves differently a ...

Creating a classification for a higher order function

In the code snippet below, I have a controller that acts as a higher order method: const CourseController = { createCourse: ({ CourseService }) => async (httpRequest) => { const course = await CourseService.doCreateCourse(httpRequest. ...

Exploring the functionality of $timeout in AngularJS

Can you explain the functionality of $timeout in AngularJS and how it sets itself apart from traditional setTimeout()? ...

Using Socket.io with NGINX has been quite a challenge as I have been struggling to properly configure the sockets

Having my backend set up with socket.io, I wanted to configure socket.io with nginx. Despite configuring nginx with the following settings, my routes other than sockets are functioning properly but my sockets are not working. server_name yourdomain.com ww ...

How can we determine if the user is on a small device and utilizing flexbox with col-sm?

Is there a method to detect when the user is on a small device? I'm looking to adjust my navigation menu based on the size of the device, similar to the col-sm functionality. ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...

Ways to retrieve a JSON element and incorporate it into a CSS styling

Can someone assist me in converting a JSON object for use in CSS? I've attempted to do this using Vue.js, creating a map legend with v-for to generate the legend. However, if there is an alternative method that allows me to take a JSON object and ins ...

Positioning a fixed div within a responsive div using AngularJS and Bootstrap

I'm currently working on a page layout that consists of a fixed sidebar on the left side and a main container taking up the rest of the page on the right. Inside this right-side container, which is a div, there are 2 elements. <div class="col-sm-1 ...

Contrasting the lib and es directories

I am seeking clarity on my understanding. I am currently working with a npm package called reactstrap, which is located in the node_modules folder. Within this package, there are 4 folders: dist es lib src I understand that the src folder contains the s ...

Interference of jQuery dialog disrupts the functioning of other functions

Clicking the OK button triggers the hideTyre() function, which then calls the SetBankFees() function. Additionally, there are two dialog boxes present - $("#dialog-immpay").dialog() and $("#dialog-SelectFees").dialog(). The challenge arises when positioni ...

Is it possible to develop a function that can verify various input values and modify their appearance as needed?

I am currently working on creating a form and faced with the challenge of simplifying my code using a function. Specifically, I want to write JavaScript code that will check all input fields in the form to ensure they are filled. If any field is left emp ...

Who is responsible for the addition of this wrapper to my code?

Issue with Sourcemaps in Angular 2 TypeScript App Currently, I am working on an Angular 2 app using TypeScript, and deploying it with the help of SystemJS and Gulp. The problem arises when I try to incorporate sourcemaps. When I use inline sourcemaps, eve ...

Issue with Datepicker not updating when triggered by event handler

Having an issue with my material-UI datepicker where the date is not updating correctly when I try to select a new one. The initial value set in useState works fine, but I want the datepicker to smoothly update when I choose a different date. You can see a ...

The setState function in the useState hook is being called only one time when triggered by an EventListener

Within my functional component, I am utilizing the useState hook to store state. When the user reaches the bottom of the page, I want to dynamically add content. To achieve this, I implemented an EventListener for 'scroll' within a useEffect hook ...

Building a Vue application with customized authentication for the Google Calendar API in JavaScript

Struggling with understanding the migration from GAPI to GIS in Vue? Google has provided a helpful document on this topic: https://developers.google.com/identity/oauth2/web/guides/migration-to-gis#server-side-web-apps Attempting to implement code from the ...

Ways to showcase an array within another array using VueJS

I encountered an issue with an API call that returns its result as an array within an array. Each nested array contains card transactions that need to be displayed. Upon examining the console output, I found: Array [ Object { "data": Array ...

Error message 'Access is Denied' occurs when using Angular.js xhr.open()

Currently, I am developing an angular web application that needs to be compatible with IE10. One of the requirements is to make a cross-domain call to our enterprise salesforce server. When using Chrome (not officially supported but commonly used for devel ...

Is it possible to create a popup window that remains fixed at the top edge of the screen but scrolls along with the rest of the page if

In an attempt to organize my thoughts, I am facing a challenge with a search page similar to Google. The search results trigger a popup window when hovering over an icon, located to the right of the search results. Here is what I am looking to achieve with ...

Tips on updating arrow button icon when clicked using jquery

I am currently working on a project where I have a button icon that I want to change upon clicking it. I am using the following jQuery code: <script> $('div[id^="module-tab-"]').click(function(){ $(this).next('.hi').sl ...

What is the best way to escape a jQuery event if a different HTML select element does not have any option selected?

When trying to exit from a checkbox's change event if a specific select element has not had an option selected, I encountered an issue. Initially, I checked the select element's value with no selection using the following code at the beginning of ...