AngularJS directives and controller scope

I'm looking to create a custom directive in AngularJS that generates a div element as a title and a ul list below it.

The title should be customizable through an attribute, while the list content is controlled by a designated controller.

Check out this fiddle for a demo of my code.

HTML:

<div ng-app="myModule">
    <my-list caption="My List" ng-controller="ListController"></my-list>
</div>

JavaScript:

angular.module('myModule', []).
controller('ListController', ['$scope', function ($scope) {
    $scope.items = [{
        caption: 'Item 1'
    }, {
        caption: 'Item 2'
    }, {
        caption: 'Item 3'
    }];
}]).directive('myList', [function () {
    return {
        restrict: 'E',
        template: '<div>' +
            '<div style="font-weight:bold;">{{caption}}</div>' +
            '<ul>' +
            '<li ng-repeat="item in items">{{item.caption}}</li>' +
            '</ul>' +
            '</div>',
        scope: {
            caption: '@caption'
        },
        link: function (scope, element) {
            element.find('li').on('click', function (evt) {
                alert($(this).html());
            });
        }
    }
}])

Looking for guidance on how to resolve this challenge.

Answer №1

made some adjustments to your controller.

  1. relocated the controller to a div

    <div ng-app="myModule"  ng-controller="ListController">
        <my-list caption="My List" list="items"></my-list>
    </div>
    
  2. corrected directive to accept list as a parameter

    directive('myList', [function () {
    return {
        restrict: 'E',
        template: '<div>' +
            '<div style="font-weight:bold;">{{caption}}</div>' +
            '<ul>' +
            '<li ng-repeat="item in items" ng-click="onClick(item)">{{item.caption}}</li>' +
            '</ul>' +
            '</div>',
        scope: {
            caption: '@caption', items: '=list'
        },
        link: function (scope, element) {
            scope.onClick= function(item){console.log(item);}
        }
    }
    }])
    

i do have one question though.

is the controller myList meant for viewing or for directives?? if it is intended for directives then

angular.module('myModule', []).
controller('ListController', ['$scope', function ($scope) {
    $scope.items = [{
        caption: 'Item 1'
    }, {
        caption: 'Item 2'
    }, {
        caption: 'Item 3'
    }];
}]).directive('myList', [function () {
    return {
        restrict: 'E',
        template: '<div>' +
            '<div style="font-weight:bold;">{{caption}}</div>' +
            '<ul>' +
            '<li ng-repeat="item in items" ng-click="onClick(item)">{{item.caption}}</li>' +
            '</ul>' +
            '</div>',
        scope: {
            caption: '@caption'
        },
        link: function (scope, element) {
            scope.onClick= function(item){console.log(item);}
        },
        controller: 'ListController'
    }
}])

Answer №2

The issue at hand, as indicated by the error message, is that you are specifying multiple directives that request an isolated scope.

To set a controller for your directive, utilize the controller property within the Directive Definition Object:

<my-list caption="My List"></my-list>

.directive('myList', [function () {
    return {
        ...
        controller: 'ListController', 
        ...

Check out the updated fiddle here

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

The PHP script is not receiving the post parameters sent in the ajax request

Help Needed jQuery.ajax({ url: 'PHPdocs/appsearch.php', data: {term:'blub'}, type: "POST", async: true, data: "text", succes ...

Learn how to manipulate data within a MongoDB database schema using Node.js and Mongoose: inserting, saving, and updating records

When inserting data into the MongoDB schema presented below, make sure that Employee name, Project name, and client name can be the same, but the employee ID must be unique. Duplicate entries are not allowed. var StatusSchema = new mongoose.Schema({ ...

Guide to modifying Button on fetch response in React Native

After receiving a response from the server, I need to adjust the button based on the friends_status field in the following response: { "responseHeader": { "type": "314", "status": "200", "message": "Successfully found the profile" }, "ne ...

"There is an issue with the payload size: request entity is too large. What is the solution for handling this in Nest

I am facing an issue where I need to send a request containing a large base64 string, approximately around 2 MB. However, the server keeps throwing an error message. How can I prevent this error from occurring: [Nest] 1666 - 11/01/2021, 1:50:58 PM ERRO ...

Create a function that will repeatedly call itself at specified intervals, increment a variable, and update the class values of elements with an id matching the current value of the

I'm attempting to create a setup that cycles through different images <div id="img_box" class="shadow" onload="imgCycle(1)";> <img id="1" class='opaque imgbox selected' src="media/img ...

"Encountering a parse error with ui.bootstrap in Angular - the beginning of

I am excited to start using the ui-bootstrap module. Take a look at my code - I believe all the imports are correct, right? <!DOCTYPE html> <html ng-app="mainApp"> <head> <meta charset="UTF-8> <title>Title of the document< ...

Using Selenium to scroll down to an element until its 'style' changes

I'm in the process of scraping a review page similar to this one. While this specific page has only a few reviews, there are others with a larger volume that require extensive scrolling. Upon observation, I noticed that when the page is not complete ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

When adding files through drag and drop, the FormData is including a blank file field in the sent

I am currently working on a photo upload page that has drag and drop functionality enabled. Below is the form code: <form id="Upload" method="post" action="sessionapi/UserPicture/Upload" enctype="multipart/form-data"> <input class="box__file ...

What steps can be taken to revert this Node.js module to a particular version and ensure it does not automatically update in

While using the Nodemailer module in node.js, I encountered a specific error that read as follows; [Error: Unsupported configuration, downgrade Nodemailer to v0.7.1 or see the migration guide https://github.com/andris9/Nodemailer#migration-guide] A ...

Obtain the content enclosed by HTML tags

Looking to extract text between html tags? Imagine having a list of cities in California, each within paragraph tags. Can you retrieve only the text inside the paragraph tags? <div class="cities"> <div><p>Los Angeles</p><h5 ...

Automatic popup updates when submitting a form in a Chrome extension

Looking to develop a chrome extension popup window that, when clicked, will present a form for users to input their name and college. The goal is to save this data in chrome storage and then replace the popup with a new window displaying a greeting message ...

How can I populate a dropdown list in JavaScript with JSON data from a file?

I am experiencing difficulties when it comes to parsing JSON files for use in a dropdown list. JSON: { "BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso", "BG": "Bulgaria", "BA": "Bosnia and Herzegovina" } The goal is to populate the dropdownlist ...

Incorporating a new function into a TypeScript (JavaScript) class method

Is it possible to add a method to a method within a class? class MyClass { public foo(text: string): string { return text + ' FOO!' } // Looking for a way to dynamically add the method `bar` to `foo`. } const obj = new MyCl ...

Ways to showcase multiple elements using introjs

I am attempting to highlight multiple DOM elements using the JS library intro.js, but I am encountering an issue. It seems that I can only define one element to be highlighted at a time. introjs.setOptions({ steps: [ { ...

Is it really necessary to still think poorly of JavaScript in 2011?

Here's an intriguing question for you. I've tested out a variety of popular websites, including Facebook, and I've noticed that many features still work perfectly fine even when JavaScript is disabled. People always used to say that JavaScr ...

Minimize all the open child windows from the main Parent window

I would like to implement a functionality where, upon logging in, the user is directed to a Main Page that opens in a new window. This Main Page contains two buttons, each of which will open a specific report associated with it in a new window when clicked ...

There is an array present with data filled in, but unfortunately, I am unable to retrieve specific elements

As I work on my WordPress 4.7.2 website, I find myself making an AJAX call. The PHP function handling this call returns an array using wp_json_encode(). When I view the data array in the success callback of the AJAX function, everything looks just as expec ...

Struggling with a character entity in Javascript? Learn how to escape it and avoid any display issues (such as showing

document.title = ("welcome &rarr; farewell"); Trying to display the arrow symbol "→" but it's not showing correctly. Any tips on how to properly escape it? ...

Working with JSON data and extracting specific information within the grades

Here is a JSON data structure that contains information about a student named Alice and her grades in various courses: { "student": [{ "cert_id": "59826ffeaa6-b986fc04d9de", "batch_id": "b3d68a-402a-b205-6888934d9", "name": "Alice", "pro ...