Using Angularjs to bind an array element within an ng-repeat inside a directive

Having trouble displaying the elements of an array using ng-repeat with a directive. The binding is not working correctly and showing empty values.

To view the code, visit http://jsfiddle.net/qrdk9sp5/

Here is the HTML:

<div ng-app="app" ng-controller="testCtrl">
    {{chat.words}}
    <test ng-repeat="word in chat.words"></test>    
</div>

And here is the JS:

var app = angular.module('app', []);
app.controller("testCtrl", function($scope) {
    $scope.chat = {
        words: [
            'Anencephalous', 'Borborygm', 'Collywobbles'
        ]
    };
});
app.directive('test', function() {
    return {
        restrict: 'EA',
        scope: {
            word: '='
        },
        template: "<li>{{word}}</li>",
        replace: true,
        link: function(scope, elm, attrs) {}
    }
});

The current output is:

["Anencephalous","Borborygm","Collywobbles"]
•
•
•   

The expected output should be:

["Anencephalous","Borborygm","Collywobbles"]
•Anencephalous
•Borborygm
•Collywobbles   

Any assistance would be highly appreciated.

Answer №1

Make sure to properly bind the word.

If you are using an isolate scope, remember to bind it with the scope property for it to function correctly.

scope: {
    word: '='
},

Here is an example of how to do it:

<test word="word" ng-repeat="word in chat.words"></test>

Check out the demo

Answer №2

let app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
    $scope.chat= {words: [
      'Anencephalous', 'Borborygm', 'Collywobbles'
    ]};
});
app.directive('test', function() {
    return {
        restrict: 'EA',
        scope: {
            word: '='
        },
        priority: 1001,
        template: "<li>{{word}}</li>",
        replace: true,        
        link: function(scope, elm, attrs) {             
        }
    }
});

To ensure your directive runs before ng-repeat and its modifications are maintained when the element is cloned, set a higher priority than ng-repeat's default of 1000.

The AngularJS Directives user guide explains the separation between compile and link functions in directives, including how ng-repeat works.

Since the current ng-repeat priority is 1000, any priority value greater than this will allow your directive to be executed first.

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

Using PHP to beautify JSON data

I'm currently working on generating JSON output for a specific JavaScript application, but I'm encountering a formatting issue that the script is not recognizing. Here's how I've structured my JSON so far: // setting up the feed $feed ...

The XMLHttpRequest is unable to load the <instagram OEMBED URL> due to the absence of the 'Access-Control-Allow-Origin' header on the requested resource

I am currently working on an OEMBED app where I need to access an OEMBED API to retrieve JSON data. My backend is built using Node/Express, and my frontend is using Angular. Below is the server-side code: var express = require("express"); var app =expres ...

Looking to access the value of a cookie using its name in AngularJS

I have a cookie in my application that needs to be read using angularJS ngCookies. After exporting the cookies from a browser extension, I found the following JSON representation: [ { "domain": "localhost", "hostOnly": true, "httpOnly": fal ...

Exploring the depths of Vue.js: Maximizing potential with nested

In my Grid component, I retrieve JSON data from a server and render it. The data mainly consists of strings and integers, but sometimes includes HTML elements like <strong>myvalue</stong>. In order to properly display the data, I use triple bra ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

Dynamic menu item created using Material UI state management

I am facing a challenge in displaying different menu items based on the gender state. Below are the constant values I am working with. const maleArray = ["A", "B", "C", "D"] const femaleArray = ["E", " ...

Retrieve the necessary controller's attributes directly within a template

Within a directive container, there is a nested directive called foo. The structure of the DOM hierarchy is as follows: <container> <foo></foo> </container> To access the container directive from the link function inside foo, de ...

Error in SO Embed Snippet Fiddle due to Bootstrap 4 JS Issue

Just wondering, any idea why the bootstrap 4 js is throwing this error: https://i.sstatic.net/J4Iq4.png when trying to embed the snippet? (No errors in the external Fiddle) Added tether.js but no luck (kept it commented). Switched to jQuery 2.2.1 on th ...

Utilizing AngularJS to dynamically bind input to a value with a filter and keep it updated

I'm facing an issue with an input element linked to an object property along with a filter. Even though I update the object.field programmatically, the displayed value in the input does not change, although the correct value is reflected in the DOM In ...

Having trouble converting response.data to a string in ReactJS

import React, { Component } from 'react' import TaskOneServices from '../services/TaskOneServices' import circle from '../assets/icons/dry-clean.png' import tick from '../assets/icons/check-mark.png' async function ...

What sets apart ".. let i = index" from "..let i as index"?

Having recently delved into the world of Angular, I've been scouring YouTube for tutorials. While watching, I noticed some developers using ""let item of items; let i as index"" while others used ""let item of items; let i = index" ...

Updating data-bind ng-model textarea in AngularJS scope is not reflecting changes

I encountered an issue while trying to reset a textarea using a function that I created. The problem is that although the scope updates as expected, the textarea bound by ng-model does not update. Below is a simplified version of the code: In Controller ...

Selecting an option from dropdown1 to retrieve a specific value from a JSON file

I currently have 2 dropdown lists to fill with data from a JSON file: $scope.categories = [ {name:"Blouse", sizes:["36","38","40","42","44","46","48","50"]}, {name:"Shirt", sizes:["36","38","40","42","44","46","48","50"]}, {name:"Pants", size ...

Struggling to comprehend JavaScript in order to customize a Google map

I'm new to the JavaScript world and having some trouble with my map styling. The map itself is displaying correctly, but the styles aren't being applied. I keep getting an error message saying I have too much code and not enough context, so I&ap ...

Connecting the input[date] and Moment.js in AngularJS

For the purpose of formulating a question, I have prepared a simplified example: ... <input type="date" ng-model="selectedMoment" /> ... <script> angular.module('dateInputExample', []) .controller('DateController', [& ...

Refresh text displayed on a button with the help of setInterval

I need help updating the text on a button with the id fixed-button at regular intervals. Here is the code I am currently using: <script type="text/javascript"> $(function() { $('#fixed-button').setInterval(function() { ...

Incorporate AJAX functionality with a simple HTML button

Upon clicking the button, the AJAX call fails to execute. Below is the HTML code for the buttons: <td><button id=${data[i].id} name="update" type="button" value="${data[i].id}" class="btn btn-primary update" ...

Combine an array of objects that are dynamically created into a single object

Having trouble transforming the JSON below into the desired JSON format using JavaScript. Current JSON: { "furniture": { "matter": [ { "matter1": "Matter 1 value" }, { "matter2": "Matter 2 value" }, { ...

Retrieving multiple arrays from a database using PHP

Hey there! Can anyone help with this issue? I am trying to select data based on their ID, but some data is not getting selected and only displayed. How can I ensure that data is selected based on their ID? It works for this array: [0] => 1 [1] => ...

Why are two vertical scrolls appearing on the screen simultaneously?

I utilized this method to hide the body scrollbar initially and then display it upon clicking a link: $('body').css('overflow', 'hidden'); $('#site').click(function(e) { $('#wrapper').remove(); $(& ...