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

Every time I attempt to log in, the code keeps generating an error message net::ERR_EMPTY_RESPONSE. If successful, it should redirect to the

The code is producing a net::ERR_EMPTY_RESPONSE error when attempting to log in. The username and password are hardcoded. I simply want the admin to input their credentials on the Employee.html page, and if they match the ones in the main.js file, redirec ...

Issues with jQuery AJAX functionality

I am in the process of incorporating some ajax functionality into my php website. I have a good understanding of jQuery, but for some reason, the value returned is always empty when I try to alert() it. Below is the code snippet that I am using: PHP: if( ...

Top tips for data manipulation

I am facing an issue with my JavaScript code that makes an ajax request to the server and receives JSON data, which is not correctly formatted for array-based manipulation. A colleague suggested a client-side solution to convert object-based JSON into arra ...

Encountering numerous errors when importing Wallet Connect / Web3 Provider

I encountered some challenges when trying to incorporate the "@walletconnect/web3-provider" JS library into my project. After installing the library along with the Web3 module using the following command: npm install --save web3 @walletconnect/web3-provide ...

What are the steps to extract information from an observable?

Having trouble retrieving data from a request? I've encountered an issue where the data retrieved inside .subscribe in an observable function is returning as undefined when trying to access it outside the function. It's quite frustrating! Here i ...

Tips for displaying an input element across multiple cells in ObservableHQ

Imagine you have the code snippet below representing a checkbox element in Observablehq: viewof myFilter = checkbox({ title: "Foo", description: "bar", options: myOptions, }) How can I display this element multiple times in different cells through ...

Issues with launching NPM Start (Having trouble with Node on Mac OS X Yosemite)

As a Rails developer, I decided to expand my skills by learning Angular JS. I came across this tutorial that seemed interesting, but I'm stuck at trying to get a node server to run. Here is the content of the npm-debug.log file: 0 info it worked if ...

Currency unique to a specific culture

Recently, I encountered an issue while working on a website that involved using JavaScript code to format currency values. Here is the snippet of code that was causing the problem: UsdAmount.toLocaleString(siteCulture, {style: 'currency', ...

Clear existing markers from the map before inserting new markers

I have a map where initially the markers load coming from the database, Then there is a time-based Ajax request that fetches new records every minute. In my code snippet, I am using setMapOnAll(null) following the guidance from the Google Maps Documentati ...

Implementing a Where Condition in JavaScript with the MongoDB whereObj

Working on a project involving JavaScript and MongoDB has led me to a specific collection named test_collection. Within this collection, there is a field/object called test_field_1 which contains test_sub_field_1 and test_sub_field_2. Currently, I am sett ...

Discovering an npm module within an ember-cli addon component

I recently encountered an issue while using ember-browserify to locate npm modules in my ember-cli applications - it seems to not function properly for ember-cli addons. This leads me to wonder: Are there alternative methods for importing npm modules into ...

implement a Django for loop within the template by utilizing JavaScript

Is it possible to incorporate a {% for in %} loop and {{ variables }} in a Django template using JavaScript DOM (insertAdjacentText, or textContent) and dynamically load data from the views without refreshing the entire page? If so, can you please guide me ...

Editing the content of a div in real-time by dynamically updating the innerHTML

Looking for a way to dynamically change the innerHTML of a contentEditable div using pure JavaScript, without relying on the Rangy library. I want the change to occur on keyup without losing cursor position or focus. Here is an example setup: <div id=" ...

Using inertia-links within the storybook framework

Hey there, just wanted to share my experience with storybook - I'm really enjoying it so far! Currently, I'm facing a challenge while implementing it in my Laravel app with Inertia. I'm trying to render a navigation link component that make ...

Navigating through the meanjs framework's routes to access the server

I am currently working on implementing a new function in my controller called "matches.server.controller" named listTeams. I have included a new route in the matches.server.route.js file as shown below: 'use strict'; /** * Module dependencies. ...

What's causing me to encounter two canvases while implementing PIXI.js in my Next.js project?

I'm facing a challenge in my game development project that utilizes PIXI.js within a Next.js setup. Currently, I am experiencing an issue where the webpage is displaying two canvases instead of one, leading to unexpected rendering issues and impacting ...

What could be the reason behind Cesium viewer's failure to show a model after I upload it?

My application features a 3D map of a city with an "Add building" button. Upon clicking this button, a model of a building should be inserted into the map. However, all I see is a selection marker at the intended location without the actual building appea ...

Setting the 'redirect_uri' for Identity Server 4 in a React JS application and directing it to a specific view using a route

After following the instructions at , I attempted to login to Identity Server from my ReactJS application. Upon successful login, http://localhost:3000/callback.html was loaded with id_token and access_token in the URL. However, I noticed that this callbac ...

Trigger AngularJS functionality upon the completion of loading a Partial routed by Express

I'm fairly new to AngularJS and recently ran into an issue that's been keeping me up at night... Our application is built on node.js and express, with all partial routing handled by Express. The problem I'm facing is this: Whenever I load ...

Is there a way in PHP to retrieve database values and display them in HTML text boxes when a button is clicked, all without

Is there a way to dynamically fetch values from a database and display them in text boxes without the need to refresh the page? Here is the PHP code snippet I have been working on: <?php include 'Connection.php'; $sql = mysqli_query($conn ...