What if I am interested in developing a directive that specifically targets custom elements and attributes?

Suppose I want to create a directive that only matches elements with the attribute amInput[type=dropdown]. How can this be achieved?

One possible approach is:

.directive('amInput',function () {
        return {
            restrict: "E",
            scope: {
                data:'@'
            },
            compile:function(tElement, tAttrs){
                if (tAttrs.type != 'dropdown') return;

                return  function link ($scope, element, attr, ctrl) {
                    var parseResult = parse($scope.data);
                }
            }
        }
    });

However, if another directive with an isolate scope for am-input[type=checkbox] is defined:

.directive('amInput',function () {
        return {
            restrict: "E",
            scope: {
                data2:'@'
            },
            compile:function(tElement, tAttrs){
                if (tAttrs.type != 'checkbox') return;

                return  function link ($scope, element, attr, ctrl) {
                    var parseResult = parse($scope.data2);
                }
            }
        }
    });

The use of angular#$compile results in an exception regarding two directives defining an isolated scope.

Error: [$compile:multidir] Multiple directives [amInput, amInput] asking for   new/isolated scope on: <am-input type="checkbox"></am-input>

Answer ā„–1

It's important for directive names to be unique, especially if they have the same restrict property. In your scenario, consider combining them into a single directive.

If you need more information on naming conventions for Angular directives, you can check out this helpful resource: Angular Directive Naming Conventions.

Answer ā„–2

After much consideration, I have arrived at a solution that distinguishes between directives using the postlink method, while prelink is utilized when everything is similar between them:

directive('amInput', function () {
    var template = {
            'dropdown' :require('./dropdown.drv.html'),
            'checkbox-group' :require('./checkbox-group.drv.html')
    };

    var  postLinkPerType = {
            'dropdown': require('./postLink-OneFromMany'),
            'checkbox-group':require('./postLink-ManyFromMany')
    };

    return {
        restrict: "E",
        require: 'ngModel',
        scope:{
            selectAll:'='
            //,...
        },
        transclude:true,
        controller: function(scope, element, attr) {
            /*for binding stuff that use by post links */
        },
        controllerAs:'inputCtrl',
        bindToController:false,
        template: function (element, attr) {
            return template[attr.type];
        },

        compile: function (element, attr, ctrl, transcludeFn) {
           return {
               pre: function (scope, element, attr, ctrl, transcludeFn) {
                    /*******************************************/
                   /* some general/init code for all collection*/
                    /*******************************************/

                   /* init options list */
                   if( attr.data ){
                       /***********/
                       /* some code just if there is some attribute*/
                       /***********/
                   }

               },
               /*the little different code that make every directive in collection different*/
               /*different by TYPE attribute*/
               post: postLinkPerType[attr.type]
           }

        }
    }

})

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

Passing data between multiple components in Vue.js and Laravel: Best practices

require('./bootstrap'); window.Vue = require('vue'); Vue.component('exampleComponent1', require('./components/exampleComponent1.vue')); Vue.component('exampleComponent2', require('./components/exampl ...

What is preventing me from accessing the hidden article using the URL with the hashname?

I've been searching for a solution, but so far nothing seems to work for me. I have a page with header and content sections. The content section is currently not visible. When I click on an item in the navigation menu, I want to hide the header and di ...

Karma issue: The application myApp has not been defined

Currently, I am attempting to run tests on the Angular seed project using a fresh installation of Karma in a separate directory. I have not made any modifications to the Angular seed project. However, I am encountering an issue where both myApp and myApp.V ...

"Using only JavaScript to target and manipulate child elements within the

I'm currently transitioning from using jQuery to pure JavaScript, and I've just started but am encountering difficulties. Specifically, I am unsure how to select child elements in the DOM. <div class="row-button"> <input type="submi ...

Tips on incorporating a class into a div generated within a contenteditable container

Take a look at this sample code: <div> Text.. <div id="editable-editor" contenteditable="true">Some Text Here...</div> </div> If you hit enter inside the #editable-editor after Some Text, it will generate a <div>Here...& ...

The SvelteKit server successfully loaded data, displaying it on the sources/index page in the Chrome

I am currently in the process of developing a basic web application that utilizes self-hosted Pocketbase on the backend and SvelteKit as a meta framework. Recently, I discovered that the data loaded by my server is visible in the browser's sources/in ...

Preserve callback function for your office.js extension

During the creation of an Office.js Word add-in, our team was looking to apply specific processing on the Document when the user actively triggers a "Ctrl +S" key combination or clicks the "Save / Save As" option. Does the Save function offer a callback ...

Increasing Divs in React with Buttons

Just getting started with React/Next and I have a query that I need help with. I'm attempting to create a button that dynamically adds more divs in real-time. Here is the code snippet I have so far: import React from 'react' const Clown = ...

ng2-idle server side rendering problem - Uncaught ReferenceError: document is undefined

Can ng2-idle be used for idle timeout/keepalive with pre-rendering in Angular 4? I followed this link for implementation: It works fine without server pre-rendering, but when I add rendering back to my index.html, I keep getting the following error: Exce ...

Make sure to wait for the scrollTo function to finish before executing any other commands

I have a sleek scrolling directive in my AngularJS app that automatically scrolls to the bottom of the page. I want this command to execute only after the scrolling has completed. Currently, I trigger the scroll function and then use $('#comment-input ...

AngularJS enables the creation of golden layout popouts for a visually appealing

I have successfully implemented golden layout in a single page application. The normal 'open in new window' functionality is working well (https://jsfiddle.net/shafaq_kazmi/xs5r6mma/6/) var myLayout = new GoldenLayout({ content: [] }, $(&apos ...

Using jQuery to Validate Input Text Control Depending on Radio Selection

How can I ensure that the input text linked to the selected radio option is filled in? For instance, in the example above: If Contact 1's Email radio option is chosen, the Email text field for Contact 1 must not be empty, while the Phone and US Mai ...

Updating the value of a Javascript variable from a separate file

Hello there! I have a file named map.php and I need to modify the center value in the code to be based on a different value provided by another JavaScript file called template.js. In the past, I was able to change other HTML values using setAttribute and q ...

Switching class on a specific element in Angular 2

My element list appears like this: <ul *ngFor="let period of periodsDate"> <li [class.show]="isShown" (click)="toggleClass()"> <a>{{ period.id }} </a> </li> </ul> ...

Unable to get HTML text input validation with RegEx to function, despite incorporating the required attribute

I am attempting to create dynamically generated text inputs that only allow for digits and an optional decimal point. I have added the required attribute but the inputs are not responding to the RegEx pattern. var howMuch = $("<input>").attr("type", ...

Encountering an error while attempting to merge webgl_interactive_cubes with pointer lock in three.js: "Unable to access properties of undefined (reading 'getHex')."

Iā€™m in the process of developing a scene with walk-navigation and interactive objects for educational purposes. To achieve this, I am utilizing the Pointer Lock Control example for walk navigation and the interactive cubes example from three.js. The proj ...

The webpage is not refreshing or reloading despite using window.location.href

When creating a refreshcart() function, the window.location.href is assigned to currentUrl. However, when making an ajax call in the else block with window.location.href = currentUrl, true; it does not successfully refresh the page. $(document).ready(fu ...

AFRAME event listener for "raycaster-intersected" capturing

I am trying to capture the event raycaster-intersected every time it happens. To handle collisions, I need to know the distance to the first entity detected, but the event only triggers the first time the raycaster hits an entity. If the raycaster contin ...

What is the process to turn my function into a promise?

Can someone help me "promisify" my custom function located in a different directory? Here is the code snippet: // app.js // include database var mongo = require('./mongo'); var promise = require('bluebird'); var u = require('./ut ...

Instructions on how to send input from a React JS user interface to a Node.js service

I am a beginner in using React JS and have a general inquiry. Typically in React, the recommended approach is to create a state object for input controls and assign its value to that input before submission. This method works well when dealing with 2-5 con ...