Angular directive that utilizes a dynamic controller name and then interpolates the controller name

Can anyone assist me with passing controller definitions to the inner directive that is nested within the outer directive? You can refer to this link for an example that may or may not work.

  1. Is there a way for Angular to interpret what is being passed as `item.ctrlName` in `script.js@46`?
  2. How can I implement the `controllerAs` syntax in the inner directive?

Answer №1

1) In order for the inner directive to have access to the parent controller, you can utilize the require parameter within the inner directive's configuration. It would look something like this:

angular.module('docsTabsExample', [])
  .directive('outer', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: {},
      templateUrl: '...', 
      controllerAs: 'outer',
      bindToController: true, 
      controller: function(scope, element, attrs) {
      }
    }
  })
  .directive('inner', function() {
    return {
      require: '^outer',
      restrict: 'E',
      transclude: true,
      scope: {
        title: '@'
      },
      controllerAs: 'inner',
      bindToController: true,  
      templateUrl: '...', 
      controller: function(scope, element, attrs, tabsCtrl) {
        
      },
    };
});

2) The current value of controller: controller references an empty function. You should replace it with a properly defined function as shown above, and ensure that you include bindToController: true.

Answer №2

After exploring different methods, I approached the solution by delving deep into abstraction. The process involved dynamically creating the entire directive configuration object and then proceeding to lazily register it.

To see the implementation, visit http://plnkr.co/edit/pMsgop6u51zPLqkfWaWT

angular.module('app', ['moduleLazyLoader'])

.controller('mainCtrl', ['$log', function ($log) {
this.list = [
  {
    name: 'asd',
    ctrl: [
      'ItemAsdCtrl',
      function () {
        $log.debug('ItemAsdCtrl');
      }
    ]
  },
  {
    name: 'xyz',
    ctrl: [
      'ItemXyzCtrl',
      function () {
        $log.debug('ItemXyzCtrl');
      }
    ]
  }
];
}])

.directive('outer', ['factoryLazyLoader', '$log', '$compile', function (factoryLazyLoader, $log, $compile) {

function controller () {}

return {
  restrict: 'E',
  controller: controller,
  controllerAs: 'outer',
  bindToController: true,
  scope: {
    list: '=list'
  },
  link: function (scope, element, attributes) {
    var directives = [];

    scope.outer.list = scope.outer.list.map(function (ele, idx) {

      var directiveSuffix = ele.ctrl[0];

        directiveSuffix[0].toUpperCase();

      var directiveName = 'item' + directiveSuffix,
        directiveAttrName = directiveName.split(/(?=[A-Z])/).join("-").toLowerCase();

      directives.push(directiveAttrName);

      factoryLazyLoader.registerDirective([
        directiveName,
        function () {
          return {
            restrict: 'E',
            replace: true,
            controller: ele.ctrl[1],
            controllerAs: ele.ctrl[0],
            bindToController: true,
            template: '<div>{{' + ele.ctrl[0] + ' | json}}</div>',
            scope: {
              item: '=item'
            }
          }
        }
      ])

      return ele;
    });

    var tpl = '<div>';

    angular.forEach(directives, function (val, idx) {
      tpl += '<' + val +' item="outer.list[' + idx + ']">' + '</' + val  + '>';
    });

    tpl += '</div>'

    // debugger;

    element.replaceWith($compile(tpl)(scope))


  }
};
}])

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

My attempts to load the .mtl and .obj files using THREE.js have been unsuccessful

I've been working on creating a 3D model viewer using three.js, but I'm encountering issues with loading .mtl and .obj files. Despite following a tutorial at , the only model that loads successfully is the female one. Here is the code snippet I ...

What is the best way to incorporate an environmental variable in my AngularJS controller?

My API Key is securely stored in my '.env' file to keep it hidden from Git. Here's a snippet of my .env file: API_TOKEN=secrettokengibberish When working on my Angular controller, I need to retrieve this variable for my AJAX call. This i ...

Is it possible to achieve avoidance of width calculation using only CSS?

Check out this link for more information. For a working version, visit: this site. The issue here is that Angular is calculating the width of the slider when the directive is processed, but since the item is not visible, it has no width. The labels on th ...

How can I halt the execution of the setInterval function in jQuery?

In my code, I have a timer function that triggers when it reaches below 1 minute. It then flashes specific text using a JavaScript function. You can see the initial setup in this jsfiddle: http://jsfiddle.net/8yned9f9/5/ $(document).ready(function(){ ...

Discover a way to retrieve the index of elements in Vue JS that are not within a v-for loop

I am interested in learning how to access the index of elements outside of a v-for loop <template> <div class="hero-text"> <h4>0{{ index + 1 }}/{{ homePageImageList.length }}</h4> </div> <VueSlickC ...

React - Issues with passing props correctly from mapped array to child component

I am currently working on a dashboard component that showcases rendered previews and code for HTML snippets. Within this dashboard component, I am utilizing the .map method to iterate through an array of snippets. Each snippet will have a pre-existing dele ...

Rewrite the .htaccess rule to eliminate "index.html" from the URL

When working on my application, I encountered an issue with redirecting from a website to open a URL link. The specific URL is: https://[site]/index.html#/Login This URL is utilizing AngularJS on the site. I attempted to redirect using '' but i ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

How can I initiate an AJAX POST request over HTTPS?

Despite my efforts, I am consistently encountering a 404 error when attempting to make an Ajax POST request. The specific error message reads: "GET 404 (Not Found)." Could this issue be related to the site's use of https? Below is the code snippet t ...

jQuery plugin stops functioning properly following the use of the jQuery display block method

In my project, I am exploring the use of divs as tabs with jQuery. Within these divs, I also want to incorporate another jQuery plugin. Currently, I have manually created these div tabs using jQuery and set the default style for second and subsequent divs ...

The ripples can be found at the bottom of the map, not at the front

Having an issue when working with Globe where Ripple rings are always appearing on the backside of the map, rather than in front of it Referencing the source code from https://github.com/vasturiano/globe.gl/blob/master/example/random-rings/index.html and ...

Updating the default value in Angular select directive

I am facing an issue with setting the default value of a select box from a controller value. Here is my controller setup: controller.item = {name: "bar1", value: 1} controller.items = [{name: "bar0", value: 0}, {name: "bar1", value: 1}] Below is my HTML ...

What is the process for sending JavaScript data to a Rails controller action?

Utilizing jQuery Shapeshift for drag and drop reordering of lists on my web application. I am looking to send the data below to my Rails controller action in order to update the list's order. Every time I drag a list, this is the output that appears ...

The act of transferring non-textual information into web-based applications

Is it possible for a user to copy and paste a selection of pixels from MSPaint into a browser-based app using JavaScript in current browsers? If not, will HTML5 make this possible in the future? Alternatively, could something like Flex or Silverlight be us ...

Is it possible to retrieve the object from a forEach loop?

Can an object be built using the results of a forEach loop? Here's my current approach: const data = {} object.rules.forEach(rule => { data[rule.name] = { body: [], type: rule.type } }) This is how I'd prefer to do it: const newData = obj ...

Passing data to server-side PHP script using AJAX technology

Currently, I'm facing an issue with passing variables to a PHP script using onclick. It seems that I am making a mistake somewhere. To demonstrate the problem, let's say I have the following code snippet in my main page: <img src="myImage.jp ...

The percentage height setting for a div is not functioning properly, but setting the height in pixels or viewport

Within a dialog box body, I am attempting to display a table and have applied a CSS class to the wrapping div. When specifying the height in pixels or viewport height units, it works as expected. However, when using a percentage like 50%, the height of the ...

Utilizing AngularJS to calculate elapsed time and continuously update model and view accordingly

Situation Currently, I am interested in developing a web application that tracks a specific data set based on the time since the page was loaded. For example, "how many calories have you burned since opening this webpage?" I am still trying to grasp the ...

Time-driven occurrences in HTML

I want to create a daily event, like an alert box or a message displayed in a window, at 10 am on my webpage. How can I achieve this without constantly checking the time and wasting resources? ...

Showing a loading animation whenever the date picker's selected date is changed

My Laravel application showcases various statistics to users. Within my front-end blade, I have set up multiple widgets, each displaying a specific stat. The widget below showcases the total number of orders. <div class="row mt-3" id="sh ...