Angularjs directive: independent scope and encapsulated elements

Why aren't the contained/child elements rendering when using an isolated scope? I suspect that the parent is not rendered yet. I tried adding a $timeout, but still no luck. If I remove the isolated scope by commenting out

 scope: {},

it works. How can I make it work with an isolated scope and render the contained elements?

Code: http://plnkr.co/edit/ZEwj9z?p=preview

'use strict';

var app = angular.module('Directives', []);

app.controller('MainCtrl', function ($scope) {
   $scope.data = [{id:1}, {id:2}, {id:3}];
});


app.directive('test', function ($timeout) {
  return {
            restrict: 'A',
            scope: {}, //if it is commented out, li would render
            link: function (scope, elm, attrs) {
                console.log('Inside link..');
            }
    };
});

template

 <div ng-controller="MainCtrl">
      <ul test>
        <li ng-repeat="d in data"> {{d}} </li>
      </ul>
    </div>

Answer №1

It seems like in order to establish a new scope for the directive, you should pass the model for creating a two-way binding:

<ul items="list">
    <li ng-repeat="item in list"> {{item}} </li>
</ul>

Directive:

app.directive('items', function ($timeout) {
    return {
        restrict: 'A',
        scope: {list:"=items"},
        replace:false,
        link: function (scope, elm, attrs) {
            console.log('Inside link..'+scope.list);
        }
    };
});

Answer №2

An isolated scope does not inherit properties from the parent scope; in this case, there is no variable data within your specific directive.

In order to access it, you can either directly use it from the parent:

<div ng-repeat="item in $parent.data"> {{item}} </div>

or establish two-way data binding:

<section directive="data">

scope: {data: '=directive'}

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

Difficulty triggering an event within a collection in Backbone.js

Having recently delved into JavaScript and Backbone, I encountered a puzzling error. Router = Backbone.Router.extend({ routes: { ":albumID": "load" }, load: function (albumID) { if (controller.collectionInitialized == true) ...

precise measurement of cell size

Here's the scenario: I have a table in ng-grid set up like this: var templateImage = '<div class="ngCellText" ng-class="col.colIndex()"><img src="images/{{row.getProperty(\'faseXD[0].fase\')}}.png"></div>&a ...

What are the steps to create a class diagram for a NodeJS application?

For my final year project, I am looking to develop an application using Node API. As we delve into drawing the class diagram, it occurs to me that unlike Java or C#, Node JS does not have a built-in class concept. What would be the most effective approac ...

The Vue router is unable to access the store state

My Vue application is utilizing vue-router and vuex. I acquire an authentication token from my API, store it in localStorage, and then push it to the store. However, when the page refreshes, the app is unable to retrieve the token from localStorage and the ...

The script is malfunctioning on Google Chrome

Below is a script that I have: EXAMPLE : <script> var ul = document.getElementById("foo2"); var items = ul.getElementsByTagName("li"); for (var i = 0; i < items.length; i=i+2) { // perform an action on items[i], which repr ...

Encountered a Socket.io issue: CONNECTION_TIMED_OUT_ERROR

I'm in the process of developing a simple HTML chat program. I've set up a node server for testing, but encountering a socket error when trying to access the HTML page. This is my first experience with Node.js and setting up a server, so it' ...

JavaScript Memoization: Enhancing Performance Through Caching

Recently, I delved into various JavaScript design patterns and stumbled upon memoization. While it seems like an effective way to prevent redundant value calculations, I can't help but notice a flaw in its implementation. Consider the following code s ...

How to stop Mouseenter event from bubbling up in an unordered list of hyperlinks using Vue 3

I've experimented with various methods to prevent event bubbling on the mouseenter event, but I'm still encountering an issue. When I hover over a link, the event is triggered for all the links as if they were all being hovered over simultaneousl ...

Puppet Master: Retrieve the inner content

Is there a way to retrieve the innerHTML or text of an element? Or even better, how can I click on an element with a specific innerHTML? The approach in regular JavaScript would be as follows: let found = false; $(selector).each(function() { if (found ...

Nuxt: The meta title for dynamic head is not defined during server-side rendering

In my nuxt project, I am encountering an issue with the meta title and description. These values are coming from nuxt/content. The data is fetched asynchronously in the index and passed to a sub component using a getter. When generating the page, the met ...

Retrieve the service variable in the routing file

How do I access the service variable in my routing file? I created a UserService with a variable named user and I need to use that variable in my routing file. Here is the approach I tried, but it didn't work: In the routing file, I attempted: cons ...

Display a dialogue box when encountering a Vuetify error. Only open the dialogue box under certain conditions

I am currently implementing vuetify into my project. The main issue I am facing is related to the dialog component, which I only want to open in case of an error. The scenario involves a button calling a backend service to save a product in the database, a ...

How to pass information from a detail page to a master page using Ionic and AngularJS?

When working with Ionic (or AngularJS in general), I am faced with a situation where I have Master/Detail pages. In the Detail page, I select some data and need to pass this data back to the Master controller. Can anyone provide guidance on how to accompl ...

The customized styling for Material Angular does not seem to properly apply to <md-card> elements within ui-views

I am trying to achieve a specific effect on the ui-views <md-card id="sidebar" flex="20" class="sche-card" layout-padding="true"> <div ui-view="card" autoscroll="false"></div> </md-card> However, I am facing an issue where the car ...

What could be the reason for one function returning undefined from identical API calls while the other functions produce successful results?

As I delved into incorporating the TMDB API into my project, a perplexing issue arose that has left me stumped. Despite utilizing identical code snippets in two separate files and functions, one of them returns undefined while the other functions flawlessl ...

The prompt "npm run build" command resulted in a 126 Vercel exit status

While attempting to upload my website with Webpack to Vercel from the repository, I encountered an error during the build process: Skipping build cache, deployment triggered without cache. Cloning completed: 2.089s Running "vercel build" Vercel CLI 31.2.3 ...

Click to stay in the background

I am currently facing an issue where opening a new tab on click redirects the focus to the child window instead of staying in the current window. I would like the popup to open without blocking and allowing me to maintain focus on my current window. The c ...

Remove data from Firebase that is older than two hours

I need to implement a solution to automatically delete data that is older than two hours. Currently, I am iterating through all the data on the client-side and deleting outdated entries. However, this approach triggers the db.on('value') function ...

The JavaScript button's onClick event is not functioning properly, despite the method executing normally

I'm currently working on creating a button using JavaScript that, when clicked, will trigger an AJAX request to some PHP code. Interestingly, I have already set up three buttons with the same functionality and they are all functioning perfectly. Wha ...

displaying a confirmation using jQuery in CodeIgniter

Hello everyone, I am a beginner in CodeIgniter and I am seeking assistance. I am attempting to create a confirmation message (div id="delmsg") using jQuery when deleting a record from MySQL database. The delete operation is functioning properly, but the me ...