AngularJS custom directive with isolated scope and controller binding

I am looking to create a directive that includes both scope parameters and ng-controller.

Here is the desired structure for this directive:

<csm-dir name="scopeParam" ng-controller="RegisteredController">
   <!-- Content goes here--> 
   {{name}}
</csm-dir>

I have a controller named "RegisteredController" defined somewhere in my application.

angular.module('app')
    .controller('RegisteredController', ['$scope', function ($scope) {
        //$scope.name should be accessible here
    }]);

Now, I am attempting to declare the directive:

angular.module('app')
    .directive('csmDir', [function () {
        return {
            restrict: 'AE',
            replace: true,
            transclude: true,
            scope: {
                name: '='
            },
            template: '<section class="layout"><ng-transclude></ng-transclude></section>',
            link: function (scope, element, attr, ctrl, transclude) {
                element.find('ng-transclude').replaceWith(transclude());
                //here I also need scope.name parameter
            }
       };
    });

However, I encounter the following error:

Multiple directives [ngController, csmDir] asking for new/isolated scope on: <csm-dir name="scopeParam" ng-controller="RegisteredController">

This error provides insight into the issue, revealing that Angular does not function as intended.

Removing the "scope: {..}" parameter from the directive and defining it in the controller is not the solution I am looking for.

Essentially, I aim to add ng-controller to a custom directive, along with additional scope variables for that controller.

How can this be achieved?

Answer №1

Make sure to enclose your directive within a container and specify the controller.

<div ng-controller="RegisteredController">
   <csm-dir name="scopeParam">
       <!--Content goes here--> 
       {{name}}
   </csm-dir>
</div>

It is not possible to have two separate scopes within a single tag.

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

Exploring the possibilities of accessing Vue.prototype within an .addEventListener function

I've been attempting to access the global object Vue.prototype.$firebase, which is declared in main.js. import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import VueTailwind from "vue- ...

Can we find a different way to address this issue with a "functional programming" mindset that doesn't involve utilizing the `forEach` method?

There has been a discussion about whether or not we still need to use forEach in JavaScript due to the availability of new language features. Some have suggested that this shift is an indirect push towards functional programming. I recently came across an ...

Sort through the API's array

Currently, I am working with the OpenWeather API's 5-day 3-hour forecast feature and encountering an issue regarding the response JSON. The array contains 40 items, each with a "dt_txt" value in the format of "2018-11-22 15:00:00". My goal is to displ ...

Tips for converting JSON object values to a string using JavaScript

Consider the following JSON object: { "id": 1, "name": "Name", "surname": "Surname", "number": "111111111" } Is there a way to transform this JSON object into a string that formats it as follows using JavaScript? Name Surname 111111111 ...

Looking to add a dynamic drop-down menu to my search bar, similar to Google search

Is there a way to create a dynamic drop-down list where, when a user enters the first letter of a country name, the list displays countries with names starting with that letter? It's similar to the functionality of a Google search bar. The country nam ...

The initial page load is experiencing issues with input type validations not functioning properly

I'm facing an issue with my text box where I only want to allow alphabets to be entered. Here is my code snippet: state ={ NomName: '', } onlyAlpha(e) { var regex = /^[a-zA-Z ]*$/; if(e.target.value === '' || regex.t ...

Encountering a Jasmine undefined error while utilizing Jasmine jQuery

Currently, I am working in the Yeoman Angular environment and utilizing Jasmine for testing purposes. In my index.html file, I have included both Jasmine and Jasmine jQuery like so: <script src="bower_components/jasmine/lib/jasmine-core/jasmine.js"> ...

Eliminating an index from a JSON array using Typescript

I'm working with a JSON array/model that is structured as follows: var jsonArray = [0] [1] ... [x] [anotherArray][0] [1] ... [e] My goal is to extract only the arrays from [0] to [x] and save them into their ...

Obtain the value of "Placeholder" using JavaScript in Internet Explorer without the need for JQuery

I have some custom Javascript code that checks for browser support of placeholders and creates them if not supported. This solution works on some older browsers, but not all, especially IE. The issue I am facing is retrieving the "Placeholder" value; curr ...

Struggling with a straightforward issue in Ajax that is proving to be a challenge to resolve

I've written a simple code to call an asmx webservice (xml). function maxTransaccion() { $.ajax({ type: "POST", url: "WebService.asmx/MAxTransaccion", contentType: "application/json; charset=utf-8", dataType: "json ...

Using AngularJS and JsonResult ASP.NET MVC to iterate over values with ng-repeat

I'm facing an issue when trying to display a list from my JsonResult Controller in Angular. Although I am able to receive the data in my Angular service, I am struggling to render it as a list using ng-repeat as it results in a large empty list. Howev ...

refresh the localstorage array using vanilla JavaScript

I am attempting to remove an element from an array stored in local storage. I am using vanilla JavaScript within a Vue.js 3 component. Here is my array: ["96", "281", "287", "415", "650", "661", & ...

Tips for accessing arrayList data within a loop in JavaScript and displaying it in an HTML <c: forEach> tag

I have an array list stored inside a javascript code block. I am looking to extract this array list and iterate through it using the html tag <c:forEach>. How can I achieve this? Currently, I am able to display the array list using <h:outputText&g ...

Tips for resetting/removing a Chart.js canvas in a React JSX element

I have encountered an issue with chart.js while working on a specific report. Whenever I switch pages to another page that includes chartjs elements and then switch back, the chart displays data labels on the data points like "x: number, y: number". Afte ...

Is there a way to identify when no rows contain specific values in PostgreSQL or node.js and return false?

Here is an example of a table: P Q t f f t f f In SQL, is there a way to return false when querying for t t, but true when querying for t f, f t, or f f? Should this be handled with node.js by first doing a select and then using if-else statements based ...

Creating an app for sending text messages and making video calls with Spring Boot technology

I am interested in developing an application with Spring Boot that allows users to make video calls and share text messages. I also want the ability to save these videos for future viewing by registered users of the app. Although I am familiar with node.j ...

NodeJS Exporting Features

A situation is in front of me: var express = require('express'); var router = express.Router(); var articles = require('../model/articles.js'); router.get('/all', function(req, res, next) { res.json(articles.getAll()); ...

Modify the properties of a particular component

I have an array of rooms filled with data: const room = (<Room points={points} scene={this.scene} key={this.rooms.length} keyV={this.rooms.length} />) this.roomData.push(room); For example, I now have 3 rooms each with their ...

Exploring the Functionality of Cookies in Nuxt 3 API Endpoints and Middlewares

Can cookies be utilized on the server side in Nuxt 3? For instance, I need to set a cookie in an API and then access its data in middleware: // ~/server/api/testApi.ts export default defineEventHandler(event => { /* setCookie('myCookie', ...

Is it possible to execute a JavaScript command before the function finishes its execution?

Is there a way to hide a button when a function starts, display some text, and then hide the text and show the button again when the function finishes? I'm struggling with this task because JavaScript doesn't output anything to the screen until ...