AngularJS directive with isolated scope does not cause any changes in the DOM outside of the directive

Exploring Angular directives with isolated scopes has led me to an intriguing situation. Upon calling a function from the local scope that alters a $scope variable's content, I noticed that it does not affect the DOM. For instance, when adding a new element to the $scope.customers list, the ngRepeat does not trigger, resulting in the section of the DOM where the ngRepeat items should be rendered remaining unaffected.

Directive snippet:

function addItem() {
    scope.add();
        items.push({
        name: 'New Directive Customer'
    });
    scope.$broadcast("refresh");
    render();
}
...
return {
  restrict: 'EA',
  scope: {
      datasource: '=',
      add: '&',
    },
    link: link
};

Local function snippet:

$scope.addCustomer = function() {
    counter++;
    $scope.customers.push({
        name: 'New Customer' + counter,
        street: counter + ' Cedar Point St.'
    });

    alert($scope.customers.length);
};

DOM section with ngRepeat:

<isolate-scope-with-controller datasource="customers" add="addCustomer()"></isolate-scope-with-controller>
<hr />
<div>
    <ul>
        <li ng-repeat="customer in customers">{{customer.name}}</li>
    </ul>
</div>

The alert() function will display that the $scope.customers array grows with each button click, yet the ngRepeat fails to update the DOM.

Complete code sample: http://plnkr.co/edit/8tUzKbKxK0twJsB6i104

My question pertains to whether it is possible to trigger DOM changes from such directives in any way?

Appreciate your assistance

Answer №1

After removing the check for event.srcElement.id in the directive's click-callback, your plunkr started working for me.

 function addItem() {
      //Call external function passed in with &
      scope.add();

      //Add new customer to the local collection
      items.push({
          name: 'New Directive Customer'
      });


      scope.$broadcast("refresh");
      render();
  }

When working with the controller, remember to use $scope.$apply to ensure the changes are reflected in the template:

    $scope.addCustomer = function() {
      $scope.$apply(function(){
        counter++;
        $scope.customers.push({
          name: 'New Customer' + counter,
          street: counter + ' Cedar Point St.'
        });

    });

Check out the updated plunkr 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

JavaScript is not designed to run a second time

Currently, I have a script set up using $(document).ready(). It works perfectly upon initial loading. However, I also need this script to execute whenever the user changes an HTML select control. Ideally, upon page load, I want the filter and sort functio ...

When examining an element in an Angular application using Chrome Dev Tools, why do I not observe raw HTML code?

Just as the title suggests, my question is: Even if browsers don't understand Angular, why am I able to see Angular elements while inspecting the DOM despite using AOT (Ahead-Of-Time Compilation) which means there is no Angular compiler in the browse ...

Steps for configuring mode as 'open' when generating a shadow element with vue-custom-element

Here is the method I used to generate a shadow component Vue.customElement('my-element', MyElement, { shadow: true, shadowCss: mystyles, }); ...

What is the best way to implement a hover feature on a Vue / Vuetify Autocomplete dropdown list?

I'm not very experienced with Vue and I'm finding it a bit complex to grasp. Perhaps you guys can provide the "best practice" or most efficient solution for my issue: I have an autocomplete dropdown box. When expanded, it shows a list with click ...

The Issue of Anti Forgery Token Not Functioning Properly with Ajax JSON.stringify Post

I have been attempting to utilize an Anti Forgery token with JSON.stringify, but despite researching multiple sources, I have not been successful. Below is my AJAX code for deleting some information without any issues. Upon adding the anti forgery token, I ...

During the click event, two distinct $.ajax requests interfere and cancel each other out

Here's a dilemma I'm facing: On my webpage, I have implemented two different click events. The first one opens a modal displaying a larger image when you click on a thumbnail picture (similar to Instagram on PC - I created an Instagram clone for ...

preventing firefox from highlighting text on a webpage

Similar Question: What's the most effective method to prevent text highlighting when clicking inside a div using JavaScript? Is there a way to prevent Firefox from highlighting content when a user clicks and drags? ...

An error is thrown when trying to retrieve Objects: Uncaught TypeError - Object function ParsePromise()

By obtaining a Document object with its id, the following code proceeds to locate corresponding sections based on the object. The document identifies a Parse object and document.toJSON converts this into a Javascript object. Furthermore, sections represent ...

Hold off on showing the image until it has finished loading

// Here's the code snippet angular .module('imgapp', []) .controller('mainCtrl', mainCtrl); function mainCtrl() { var vm = this; vm.first = { title: 'Image 1', url: 'http://www.image-mapper.com ...

How can I prevent receiving redundant data and effectively manage my data?

I am currently working on adding offline support to my app. The logic I am following is to first check if there is cached feed data available. If the data is present, it will set the feeds to that cached data and display it from the cache. However, it will ...

Arranging an array of objects from the Fetch API into rows and columns in Bootstrap 4 by utilizing a foreach loop to iterate through the array

I am currently retrieving data from an external API, which returns an array of objects. Each object contains details of characters from the Harry Potter movies, and there are a total of 50 objects in the array. I am using a foreach loop to iterate through ...

Troubleshooting React and Material-UI: Adjusting <slider> component for use with personalized data

I am facing a challenge with using the Material-UI slider to showcase API data. The unique aspect here is that the slider is intended for displaying data without any interactivity. Encountering an error message: Slider.js:91 Uncaught TypeError: nearest.to ...

Oops! An error occurred while trying to load the myApp module. The module 'ui.bootstrap' is missing and causing the failure

When using Firefox, I encountered the following error: SyntaxError: syntax error xml2json.js:1 SyntaxError: syntax error ui-bootstrap-tpls-0.13.0.js:1 Error: [$injector:modulerr] Failed to instantiate module myApp due to: [$injector:modulerr] Failed to in ...

Synchronize Protractor with an Angular application embedded within an iframe on a non-Angular web platform

I'm having trouble accessing elements using methods like by.binding(). The project structure looks like this: There is a non-angular website | --> Inside an iframe | --> There is an angular app Here's a part of the code I'm ...

Exploring the parent scope in handlebars.js partials

Is there a way to access the parent scope from a partial using #each in Handlebars? Main template: (out of each = {{index}})<br> {{#each someItem}} (in each, but not on partial = {{../index}}) {{>part}} {{/each}} Partial: <div class="part ...

Tips for maintaining consistent width of a div:

My current project involves designing a website that displays various quotes, with each quote rotating for a specific amount of time. However, I'm facing an issue where upon loading the page, the first quote triggers the appearance of a scrollbar, mak ...

Incorporating personalized CSS and JavaScript into Shopify

Currently, my project involves integrating vertical tabs into a Shopify page that is utilizing the 'Atlantic' theme. Since this particular theme doesn't come with vertical tabs built-in, I have incorporated external JS and CSS files known as ...

React Native (or React) utilizes separate TypeScript modules to detect and respond to style adjustments for dark mode

Objective: Add a dark mode feature to a react native application. A brief overview of the system: File structure: Profile.ts ProfileCss.ts constants.ts In my app, I've organized styles in separate .ts files and exported them as modules to keep them ...

Innovative react route

Currently, I am in the process of learning about dynamic react routes. In the code example I am working on, there are different buttons for each task. The goal is to render the WorkDetails component when a button is clicked. However, it seems to not be fun ...

What is the best way to simulate an angularJS service using $resource with a custom action?

https://docs.angularjs.org/api/ngResource/service/$resource After examining the $resource API, it is evident that there exists a custom action within the method that can be invoked. The question that arises is how to create a mock service that incorporates ...