Creating a unique directive specifically designed to be used within an ng

I have a unique custom directive that I implemented in AngularJS. The directive is called within an ng-repeat loop, as shown below:

The array of objects, selectedMealCalc.calculated_foods, is aliased as 'items'

 <!-- CUSTOM DIRECTIVE -->
    <div ng-repeat="option in [0,1,2,3,4]">
        <meal-option option="{{option}}"
                     items="selectedMealCalc.calculated_foods"
                     selectedmealcalc="selectedMealCalc"></meal-option> </div>
    <!-- CUSTOM DIRECTIVE -->

The custom directive code created in AngularJS is structured as follows:

'use strict';

    angular.module('nutriApp').directive('mealOption', ['$compile', function($compile) {
      return {
        restrict: 'E',
        templateUrl: 'views/checkins/meal-options.html',
        scope: {
          option: "@",
          items: "=",
          selectedmealcalc: "="
        },
        controller: ['$scope', 'Food', function($scope, Food) {
          $scope.sumFood = {};
          $scope.summerizeOption = function(foods) {
            if(foods.length > 0){
               $scope.sumFood = Food.summerize(foods);
            }
            return $scope.sumFood;
          };
        }]
      };
    }]);

The HTML structure for the directive looks like this:

<div class="row" ng-init="filteredItems = ( items | filter: { food_option: option } )" ng-controller="CheckinsPlansCtrl">
  <div class="col-md-12" ng-show="filteredItems.length > 0">
    Option {{ option }}
    <table class="table table-calculo table-striped">
      <thead>
        <tr>
          <th>Food</th>
          <th>Amount</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="foodCalculation in filteredItems track by $index">
          <td>{{foodCalculation.food.name}}</td>
          <td>{{foodCalculation.gram_amount}} g</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

However, when I update the

selectedMealCalc.calculated_foods
, the custom directive does not automatically refresh. To see the changes, I need to close and reopen the modal on my page.

Answer №1

In reference to a comment on this post about a Custom directive inside ng-repeat, it was suggested to remove the use of ng-init due to its intended purpose of only initializing a property on the scope, with recommendations against its usage based on another answer found in Does ng-init watch over change on instantiated property like ng-model does?

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

When you click on the button, the section will not be displayed

I'm facing an issue with my code. I have a set of five buttons and corresponding sections. When a button is clicked, the active and active-btn classes are supposed to be added to that button as well as the corresponding section element with the same i ...

Each div will display the same image twice when loading the image

I have a grid where images are dynamically loaded with a link to a lightbox. Currently, this is how I am achieving it: $(".selection_thumb").each( function(i) { $(this).append("<a data-lightbox='image-1' href='img/folder/folder/"+(++ ...

The variable in ng-init within ng-repeat becomes desynchronized

I used the ng-repeat method to list some items and included a nested ng-repeat. To keep track of my outer $index, I utilized ng-init. <div class="row" ng-repeat="product in products" ng-if="$index % 2 == 0" ng-init="current = $index"> <div c ...

The server is unable to process the request with parameters for the specified URL

I've been encountering an error every time I try to post something. articlesRouter.post('articles/:target', async (req, res) => { const target = req.params.target.replaceAll("_", " ") const article = await Arti ...

Tips for sending a PHP JSON array to a JavaScript function using the onclick event

I am trying to pass a PHP JSON array into a JavaScript function when an onclick event occurs. Here is the structure of the PHP array before being encoded as JSON: Array ( [group_id] => 307378872724184 [cir_id] => 221 ) After encoding the a ...

In a designated paragraph, set the display of all <span> elements to none using JavaScript

I have a long paragraph with over 10,000 lines of text and I need a way to quickly remove all the lines without hiding the entire paragraph. Specifically, I want to hide each line individually by changing the span style from "display:block" to "display:non ...

Exporting ExpressJS from a TypeScript wrapper in NodeJS

I've developed a custom ExpressJS wrapper on a private npm repository and I'm looking to export both my library and ExpressJS itself. Here's an example: index.ts export { myExpress } from './my-express'; // my custom express wrap ...

What is the best way to sort a table by column index using HTML?

I find myself in a situation where I am not well-versed in HTML, Javascript, and CSS. Here is the scenario: <div class="table"> <table class="display-table"> <thead> <tr> ...

When employing useEffect, clearInterval cannot halt the execution of SetInterval

My attempt to create a function that initiates a countdown when the isPlaying variable is true and stops when it's false has not been successful. Instead of working as intended, it starts multiple intervals concurrently. The value of isPlaying changes ...

Launch a link in the system browser from an Ionic application

When users click on a link in my app, I want it to open in the system browser of their device. However, I'm running into an issue where the link opens both in the system browser and within the app itself. I only want the link to open in the system bro ...

What is the best way to smoothly insert an item into a nested object within the state of a React component

Trying to create a complex array using react hook: const [strategy, setStrategy] = useState([leg]); Here's how the `leg` object is defined: const leg = { entry: { conditions: [], actions: [""], }, exit: { conditions: [], ...

What is the best way to compare dates in PostgreSQL timestamp with time zone?

In my PostgreSQL database, there is a field labeled as "timestamp with time zone compare" Currently, I am trying to implement a data range comparison using JavaScript var start = Date.UTC(2012,02,30);//1333065600000 var end = Date.UTC(2013,02,30); //136 ...

swapping the final word in a string with Node.js or JavaScript

var str = "Demo Docs Version 1.0.1"; var gotWord = str.split(" ").splice(-1)[0] str = str.replace(gotWord, "testing"); console.log(str); If there is a space between words, I can replace the last word. But how do I replace the last word when ...

Selenium was unable to scroll a sidebar or container

I'm just starting out with selenium and python. I'm trying to scrape the content from a website that has a sidebar (container), and I need to copy its content multiple times while scrolling until I reach the end of the container. However, I&apos ...

What is the best way to compare a JSON object and a string in JavaScript?

Currently, I am working on developing the website layout for . Most of the data retrieval and display have been successful so far. However, when attempting to filter my search results to show only stop names associated with Subways, I encountered some err ...

Make sure to update the value of a Mongoose document only if it has been

I am looking to update a specific value in the document only if it is newly defined. If the value is not defined, I want to leave it as it is in the document. For example: If this particular document exists in the database: { "_id": "592c53b3bdf350ce00 ...

Store the response data in a global variable or forward it to another function in Node.js using Express JS

I'm currently working on a function that makes a post request to an API (app.post), sending a token and a URL for redirection to webpay. The challenge I'm facing is saving that token in a global variable so that it can be accessed by another func ...

How can I apply a jquery method to a variable when JavaScript already has a method with the same name?

Is it possible to call the .which function on a character without needing to differentiate between browser types by using the jQuery .which method, which supposedly normalizes for browser discrepancies? I know that the inherent javascript method is also ...

Issues with Angular $http service retrieving data from a .JSON file

Below is the code snippet for my http service: app.controller('StoreController', ['$http', function($http){ var store = this; store.products = []; $http.get('/store-products.json').then(function(data){ sto ...

The Ajax request is not being triggered when using a different form submit method

Being a tech enthusiast, I have developed a handy function: function blur_slide_visit_count(){ $.ajax({ type: 'POST', url: 'add_save_slide_visitor_count.php', async: false, data: { fillvalue: fieldAr ...