Guide on how to update the controller value in AngularJS directive to trigger data retrieval

I currently have multiple controllers responsible for fetching data from the server. One example of such a controller is shown below:

var vm = this;
  
  var month = 1;
  
  loadStatusCount();
  
  function loadStatusCount() {
      vm.summaryCount = [];
      
      statusCountService.setMonth(month);
      statusCountService.setType('e');
      statusCountService.getStatusCount()
                  .then(function (report) {
                      applyCount(report);
                  });
  }
  
  function applyCount(report) {
      vm.summaryCount = report[0];
  }
  
  vm.getTotal = function () {
      var total = 0;
      for (var i = 0; i < vm.summaryCount.length; i++) {
          var count = vm.summaryCount[i].count;
          total = total + count;
      }
      return total;
  }
  

The rest of the controllers have similar code, the only difference being the type parameter.

As of now, I have a directive that displays a template.

monthlyReportApp.directive('statusCount', function () {
      return {
          restrict: 'AE',
          replace: false,
          templateUrl: 'Scripts/app/views/templates/status-count-template.html',
          link: linker
      }
  
      function linker(scope, el, attrs, ngModel) {
          scope.title = attrs.title;
          scope.class = attrs.class;
      }
  });
  

I utilize this directive in my HTML like so:

<div status-count data-class="fa fa-check-square-o" data-title="Prior Auth Count" class="panel panel-default" ng-controller="PACountCtrl as ctrl">

          </div>
  

While it's not a pressing issue, I am interested in reducing redundancy. Hence, instead of creating multiple similar controllers, how can I have a single controller that can be utilized by the directive to fetch data with different type values for various div elements?

Answer №1

To dynamically pass the attribute you want, consider using the type attribute. If you plan on using this directive multiple times, ensure that the directive has an isolated scope to increase reusability. Modify your directive to have an isolated scope for better component reusability.

Avoid assigning a controller to the DOM using ng-controller when you already have a directive in place. Remove it from the DOM and apply the controller from the directive itself. Pass the statusType through the directive's attribute so it can be accessed within the isolated scope of the directive. Use scope.statusType in your directive to access the value and adjust your code accordingly to

statusCountService.setType(scope.statusType);
.

When using the controllerAs syntax within your controller and isolating the scope, the scope is not directly bound to the this context of the controller. To address this, use the bindToController property, which employs the angular.bind API method to bind all the scope variables to the controller's this context. Angular 1.3+ offers bindToController: true, while angular 1.4+ simplifies this process by introducing the bindToController property to handle isolated scope and binding mappings to the controller's context.

Now, let's explore how to pass the statusType to the directive. There are various methods to achieve this, but the most commonly used approaches will be highlighted. One way is to define a scope variable within the controller where the directive element is located like $scope.statusType = 'e'. Then, on the directive element, use status-type="{{statusType}}" with @ for one-way binding to pass the interpolated scope variable inside the attribute. Alternatively, you can directly pass an expression like status-type="{{'e'}}" to evaluate as a string.

Remember to utilize bindToController: true to access the isolated scope values within your directive's controller context (this).

Markup

<div status-count data-class="fa fa-check-square-o" 
   data-title="Prior Auth Count" 
   class="panel panel-default"
   status-type="{{statusType}}">
</div>

Directive

monthlyReportApp.directive('statusCount', function () {
    return {
        //require: 'ngModel',
        restrict: 'AE',
        replace: false,
        templateUrl: 'Scripts/app/views/templates/status-count-template.html',
        link: linker,
        controller: 'PACountCtrl',
        controllerAs: 'ctrl',
        //angular 1.3 + code need below to things scope: {}, bindToController
        scope: {
            statusType: "@"
        },
        bindToController: true
        //angular 1.4 + code need only bindToController
        /*
        bindToController: {
           statusType: "@"
        }
        */
    }

    function linker(scope, el, attrs, ngModel) {
        scope.title = attrs.title;
        scope.class = attrs.class;
    }
});

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

Unusual increase in the Date() function hour on March 12, 2017

I encountered an issue where creating a new Date() object for March 12, 2017 with the hour set to 2am displays as 3am when using getHours(). The expected output should be 2am. Could there be an error in my code? I have highlighted the problematic section ...

Issue arises when Protractor is unable to compare a variable with a web element due to unresolved promises

My strategy for this examination was to extract the inner text of an element, modify it, and then verify that the change had taken place by comparing the element with the variable. var fixedValue = element(by.xpath('/html/body/section/div/section/sec ...

A vertical line in Javascript extending upward from the base of an element

Is there a way to create a design where an infinite vertical line extends from the bottom of a circle (or in my case, a rectangle) without using css :after or pseudo-elements? I would like the line to be its own element and not limited by the restriction ...

Difficulty with AngularJS pagination and encountering errors when trying to read the property 'slice' of an undefined value

Could someone please help me with this issue I'm facing? Here is the code snippet: (function () { var app = angular.module('store', ['ui.bootstrap']); app.controller('StoreController', function ($scope, $http) ...

Differentiating a path element in SVG by dynamically adding color using d3 and react

I have a unique SVG icon: <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <circle cx="12" cy="12" r="12" /> <path class="svg-fill" d="M12,2A10,10,0,1,0,22, ...

Provide the identification number of a specific row within the modal

I am trying to pass the id of a specific row into a modal popup Link code: <a href="#myModal" class="btn btn-default btn-small" id="custId" data-toggle="modal" data-id="<? echo $row['id']; ?>">Resume</a> Modal code: <div ...

A guide on using Material UI - InputLabel in JavaScript

I'm currently integrating a form from this Codepen link into my project built with Codeigniter. However, I am encountering issues after incorporating material-ui into the CodeIgniter framework. The problems I am facing include an invalid token and an ...

What is the best way to transform a date such as '2021-06-01T11:17:00-07:00' into the corresponding date and time for a specific location (New Delhi) using JavaScript?

How can I convert a date in the format '2021-06-01T11:17:00-07:00' to ISO standard? What does this format represent? let date = new Date('2021-06-01T11:17:00-07:00'); console.log(date.getHours() + " :" + date.getMinutes()); I ...

The error message indicates that the property 'current' is not found in the type '[boolean, Dispatch<SetStateAction<boolean>>]'

During my React/Typescript project, I encountered an issue involving cursor animations. While researching the topic, I stumbled upon a CodePen (Animated Cursor React Component) that functioned perfectly. However, when attempting to convert it into a Types ...

Unlocking the data within an object across all Components in Vue

Recently, I've started using Vue and encountered a problem. I'm trying to access data stored inside an Object within one of my components. To practice, I decided to create a cart system with hardcoded data for a few games in the app. Below is the ...

Error due to PlatformLocation's location dependency issue

My AppComponent relies on Location (from angular2/router) as a dependency. Within the AppComponent, I am using Location.path(). However, when running my Jasmine test, I encountered an error. Can you help me identify the issue with my Jasmine test and guide ...

The function Firebase.database() is unavailable in the Sails Service

I have developed a service named Firebase.js, and I am attempting to utilize it from my Controllers by using Firebase.database. However, I am encountering an error stating that Firebase.database() is not a function services/Firebase.js var admin = requir ...

Display an additional HTML page without altering the existing one

First of all, I would like to apologize for my poor English. Attending a French school didn't provide much opportunity to practice other languages. I have a header.html on my website that I am unable to modify because it is not owned by me. However, ...

Changing a JavaScript array by including a numerical value

Here is my original dataset... [{ month: 'Jan', cat: 'A', val: 20 },{ month: 'Jan', cat: 'B',' val: 5 },{ month: 'Jan', cat: &ap ...

Utilizing ng-file-upload for seamless integration with WebService

Struggling to implement zip file uploading functionality on a server. The client side is AngularJS, while the server side is C# ASP.NET, but encountering issues in making it work. The code on the server-side appears as follows: [System.Web.Script.Service ...

Error: Issue transferring data to controller from Ng-Style

Currently, I am developing an application using Ionic and AngularJS. In this project, I am using ng-repeat to populate the results and want to display different colors based on certain criteria. Initially, I managed to achieve this using inline ng-style c ...

Automating testing with WebdriverIO in scenarios where JavaScript is turned off

Is it possible to launch the browser with JavaScript disabled in the WebdriverIO framework? I am looking to automate a scenario that requires JavaScript to be disabled. However, when I try to disable JavaScript manually in Chrome or Firefox and run WDIO s ...

Converting a TypeScript nested dictionary into a list of strings

I am currently working with a nested dictionary and my goal is to convert it into a list of strings. For example, the initial input looks like this: var group = { '5': { '1': { '1': [1, 2, 3], ...

AngularJS - Managing Multiple State Parameters

Currently, we are in the process of learning AngularJS and are facing difficulty with a specific issue. We aim to select a product type and utilize the formData value ("productType":"1") image1 to accurately display the JSON product data associated with th ...

Separate the selected option in the TEXTAREA by commas to make it easier to

Can you assist me with integrating this example? I have the following elements: When adding a textarea, I require an option to be selected and separated by a comma. For instance: Here I will select an option: Subsequently, this chosen option must be ad ...