When the directive manually replaces the element's content, ngRepeat fails to remove the old entries

I created a directive that utilizes different templates based on the state of the scope as shown below:

app.directive('foo', function($compile) {
  return {
    restrict: 'E',
    scope: {
      bar: '='
    },
    link: function(scope, element) {
      var tpl = scope.bar == 'foo' ? '<li><strong>{{bar}}</strong</li>' : '<li>{{bar}}</li>'
      element.replaceWith($compile(element.html(tpl).contents())(scope))
    }
  }
});

When using this directive within an ngRepeat loop and the array being used changes, the new elements get rendered but the old ones remain visible.

<ul>
  <foo bar="bar" ng-repeat="bar in bars"></foo>
</ul>

Check out the live demo here: http://plnkr.co/edit/UnsrjPh8kW27bK8RbPgY

Could someone please advise me on what I might be doing wrong?

Answer №1

The reason for this occurrence is that ng-repeat and directive each create their own scope. Give it a try by using the directive inside the ng-repeat, as it has worked successfully for me.

Here is the HTML code snippet:

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <p><button ng-click="changeBars()">Change bars</button></p>
    <ul>
      <li ng-repeat="bar in bars"><foo bar="bar">{{bar}}</foo></li>
    </ul>
  </body>

And here is the directive script:

app.directive('foo', function($compile) {
  return {
    restrict: 'E',
    scope: {
      bar: '='
    },
    link: function(scope, element) {
      var tpl = scope.bar == 'foo' ? '<p><strong>{{bar}}</strong</p>' : '<p>{{bar}}</p>'
      element.replaceWith($compile(element.html(tpl).contents())(scope))
    }
  }
});

You can find a working example at this link.

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

Utilizing jQuery functions within Vue components in Quasar Framework

I've recently started delving into web app development and I'm encountering some basic questions regarding jQuery and Vue that I can't seem to find answers to. I have an application built using the Quasar Framework which frequently involves ...

Preventing autoscrolling in Ionic's dual side menu template when additional content is added

Could anyone kindly assist me in figuring out why the autoscrolling of the content is not functioning correctly? Whenever the button on the header is clicked, a new message will be included in the main content. However, once the number of lines exceeds wha ...

Developing web applications using AngularJS and Web API allows for customization of error handling by utilizing

Here I have a simple form that includes only one input field for the user's name. However, I want to make sure that there are no duplicate entries in the table. I can easily check this on the server side and send a custom message in the response head ...

Executing Javascript in a Bootstrap 4 modal using Rails

I am working on a Rails 5.1 application where I'm implementing a patient record creation functionality using Ajax within a form using coffeescript/JS. The code I have been using for this task works seamlessly: _form.html.erb <div class="modal fad ...

Having trouble injecting HttpClient in a hybrid AngularJS/Angular app that has been upgraded with ngUpgrade? You may come across the error message "NullInjectorError: No provider for http_HttpClient!"

My AngularJS/Angular hybrid app, upgraded with ngUpgrade, has been functioning well. The new Angular components (downgraded) work seamlessly in the AngularJS app. However, I'm encountering an issue where the HttpClient module fails to instantiate. I ...

What is the best way to set the active class on the initial tab that is determined dynamically rather than a static tab in Angular?

I'm currently facing a problem with ui-bootstrap's tabsets. I have one tab that is static (Other) and the rest are dynamically added using ng-repeat. The issue I'm having is that I can't seem to make the first dynamically loaded tab act ...

Convert a prop into a data attribute using Vue.js 2

I have a basic component being displayed as <House :_people="[{'name': 'Kevin'}, {'name':'Bert'}, {'name': 'Timmy'}]"></House> The structure of the component is like this: <templ ...

"Exploring the synergy of NodeJS: incorporating callbacks within promises

Currently, I am in the process of logging into two different services and I am tasked with pushing both responses to an array. To achieve this, I have begun by creating a promiseResult which contains two promises for the login operations: var promiseR ...

Ajax transmits an array of data to the server

My table contains dynamic data with input fields for each item. I need to send the input field values along with the item's ID to the backend. Encountered Issue When making an AJAX request, the data sent as an array is not coming out as expected. Cod ...

A method for determining a running total from an array object in JavaScript/Typescript and presenting the result at each step using HTML

Currently, I am working on a MEAN stack project and dealing with an array setup like this: savings: any = [300, 450, 350, 500] Additionally, there is a variable named savings_bf that holds the value of savings brought forward retrieved from a database as ...

Modify the index in the creation of a json

I am trying to create a JSON object using the code below: var myJSONObject = []; var id = "1", value = "I'm a value !"; myJSONObject.push({id:value}); When I display this construction, it shows: [{"id":"I'm a value !"}] However, I want it to d ...

Exploring the Power of ng-class with Multiple Conditions in AngularJS

Is it possible to add an additional condition to my ng-class true/false statement in AngularJS when using ng-repeat? <tr ng-repeat="data in myData" ng-class="{true: 'green', false: 'red'}[data.IsPositive]"> <td> ...

Set focus on Bootstrap modal when closing the popup near the input field within the body

Hello fellow members of the Stack Overflow community! I'm trying to make sure that when users click on a Bootstrap modal window, the input field automatically gets focused. I've attempted the code below but it's not working as expected. Any ...

"Return to previous view with the zoom back feature in CanvasJS

How can I implement a zoom back button in CanvasJS using jQuery or normal JavaScript? I've been attempting to place it near the ones in the top right corner, but something seems to be amiss. Alternatively, is it feasible to enable zooming in and out ...

"Nested AngularJS controllers: a deep dive into the world

Recently, I've been delving into the world of AngularJS and I can't shake the feeling that my approach to the paradigm might be a bit off. I have a controller for managing panes (linked to an ng-repeat) which tracks which panes the user has open ...

Flask's JSON data format

When it comes to fetching data from a URL generated with Flask and not by me using AngularJS and Restangular, I seem to be encountering some issues. The JSON data I have is as follows: {"patients": ["{\"_id\": {\"$oid\": \"5677d63 ...

Create a reusable React widget in a JavaScript file and integrate it into an ASP.NET MVC project

Is there a way to create a widget with the React library and compile it into a single JavaScript file for reuse in any non-React application (particularly in ASP .NET)? ...

Is there a way to iterate through objects and add new properties to them?

I am trying to achieve the following object: let newPost = { title: "Post 1", Content: "New content" } with the code below: let newPost = {}; let postData = $(".post-data").each (function(index) { newPost.title = $ ...

What could be causing the repetition of the same cookie in my request header when using jQuery ajax?

Stuck in a dilemma for hours now, seeking assistance or suggestions from anyone who can help me out. To sum it up, I have an asp.net web api application where I am trying to fetch data from a web api and populate multiple dropdown lists on a page using jQ ...

Error: The 'in' operator cannot be utilized to search for 'length' in the Kendo UI framework

I am encountering an error while using Angular 1.4, jQuery 1.11.3, and the latest Kendo UI. I'm wondering if this issue is a known bug to Telerik. The only Kendo controls present on the page are kendo-multi-select and kendo-date-picker. TypeError: C ...