Tips for sending a set to a directive in angular.js?

Forgive me for my confusion.

I am passing the name of a collection to my directive:

<ul tag-it tag-src="preview_data.preview.extract.keywords"><li>Tag 1</li><li>Tag 2</li></ul>

This is how the directive is defined:

app.directive('tagIt', function (){
    return  {
        restrict: 'A',
        link: function(scope,elem, attr) {

            elem.tagit();
            console.log(attr.tagSrc); //the name of my collection, but how do I access it?
        }
    }
});

How can I access my collection from the directive and ensure that the directive is called when the collection is populated? Here's an example of how

preview_data.preview.extract.keyword
is populated:

app.config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
    console.log('config');
    $routeProvider.when("/", {
        templateUrl: "/templates/addItem.html",
        controller: "AddItemController",
        resolve: {
            loadData: addItemCtrl.loadData

        }
    });
});

var addItemCtrl=app.controller("AddItemController", function ($scope, $route, $sce, Preview) {
    var title = decodeURIComponent($route.current.params.title);
    var ua = decodeURIComponent($route.current.params.ua);
    var uri = decodeURIComponent($route.current.params.uri);
    $scope.preview_data = {
        uri: uri,
        title: title,
        ua: ua
    }
    //pass parameters to web preview API

    Preview.get(uri, ua, title).then(function (data) {

        $scope.preview_data.preview = data;
        if (data.embed.html) {
            $scope.preview_data.preview.embed.html = $sce.trustAsHtml(data.embed.html);
        }
    }, function (data) {
        alert('Error: no data returned')
    });


});

Answer №1

To enable iteration between tags, you must define the variable in the directive scope and specify the template accordingly:

        template : '<li data-ng-repeat="tag in tagSrc">{{tag.name}}</li>',
        scope : {
          tagSrc : '='
        },

The updated version of the directive looks like this:

   app.directive('tagIt', function (){
    return  {
        restrict: 'A',
        template : '<li data-ng-repeat="tag in tagSrc">{{tag.name}}</li>',
        scope : {
          tagSrc : '='
        },

        link: function(scope,elem, attr) {

            console.log(attr.tagSrc); 
        }
    }
});

The '=' attribute indicates two-way binding with the array provided in the HTML declaration of the directive.

Find a working example on Plunker.

Refer to this article for more information on directive attributes and life cycle.

I hope this explanation is helpful.

[EDIT]

If you simply want to iterate through the array without customizing list items behavior, use the ng-repeat directive as shown below:

<ul>
     <li data-ng-repeat="tag in tags">{{tag.name}}</li>
<ul>

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

Retrieving a MongoDB collection using its unique ID

Here's a query that may seem straightforward. I have two collections in MongoDB - one named "users" with an objectId, and the other named "listings" which has the userId. I am looking to retrieve documents from the listings collection by searching fo ...

Why does my ForEach function in ReactJs automatically execute without being called?

I am creating a function with a ForEach loop that automatically executes and renders the screen without being called. My goal is to have the startGame function update the element at position [1] of the array to be 5 when I click on it. However, as soon as ...

Tips for creating a smooth scrolling header menu on a standard header

<script> $(document).ready(function(){ $(".nav-menu").click(function(e){ e.preventDefault(); id = $(this).data('id'); $('html, body').animate({ scrollTop: $("#"+id).o ...

An error has occurred: [$injector:modulerr] Unable to create module xxApp because: Error: [$injector:nomod] Module 'xxApp' does not exist

After running the gulp task to uglify my application controller files, I encountered an error. In a previous project, the same gulp uglify code worked without any issues, but that project did not include any ES6 commands. Now I am using the 'gulp-ugl ...

Retrieve data from a local JSON file and showcase it in a list within a Next.js project. The error "Property 'data' does not exist on type String

Having trouble displaying the names of crates (which are filled with records/albums) from a local JSON file. The names aren't showing up and I'm wondering if I should be using params or if perhaps not stringifying the JSON would help. Visual Stud ...

insert the "tr" element directly following the button

I am looking for a way to allow the user to add another input file right next to the button, so they can select and send multiple files at once. https://i.sstatic.net/TI4eJ.png I have tried using various solutions I found during my search but none of the ...

I'm having trouble with my react-big-calendar not updating when I switch between day, month, or week views -

Why won't my calendar change to the week view when I click on that section? https://i.stack.imgur.com/gh2aO.png In the screenshot above, my default view is set to month, but when I attempt to switch to week, it only highlights the option without cha ...

What methods can be used in VueJS to restrict users from entering numeric values?

I am struggling to create a validation that prevents users from inputting numeric values into a textbox. I have tried using a native JavaScript solution, but it does not seem to be working on my end. In my textbox, I have set up this trigger v-on:keyup=" ...

Using JQuery to access the element within a span

I am completely new to jQuery and still learning as I go. Here is a snippet of the code I'm working on: <div class = 'buttons'> <span> <input type='button' value='BUTTON1' id='button1'> ...

What's causing this sluggish performance?

I'm in the process of developing a Google Chrome extension and I can't help but wonder why window.onload = loadPage; function loadPage() { document.getElementById('nav-robux-amount').innerHTML = '0'; console.log(" ...

Issues arising in Angular following the utilization of services

After successfully working in Angular without employing any service, I encountered a roadblock when attempting to transition my code into a service. Now, Angular seems to have ceased functioning altogether. With multiple files at play, I turned to plunker ...

I keep encountering the following error message: " ERROR Error Code: 200 Message: Http failure during parsing for http://localhost:3000/login"

My Angular Login component is responsible for passing form data to the OnSubmit method. The goal is to send form data from the front-end application and authenticate users based on matching usernames and passwords in a MySQL database. ***This login form i ...

assisting with the transition effect using CSS3, JS, or jQuery

I am looking to alter the background-image of this particular image when transitioning to another one from my images folder, similar to this example. Below is the code that I have: CSS .image { position: relative; overflow: hidden; -webkit-tr ...

Using three.js to add an image onto an already existing object

I attempted to modify the appearance of an object by adding an image, but all my tests resulted in a white object... The goal is simply to apply an image to the entire object. Here is my test code: var obj = scene.getObjectByName('wall_20_118') ...

The useSelector value remains undefined within the handleSubmit button in a React component

Once a user fills out and submits the form, the action is triggered to call the API. Upon returning the postId, it is stored in the reducer. The main React component then utilizes useSelector to retrieve the latest state for the postId. However, when attem ...

Automatically trigger a popup box to appear following an AJAX request

I am currently working on a time counter script that triggers a code execution through ajax upon completion. The result of the code should be displayed in a popup box. Below is the code snippet I am using: var ticker = function() { counter--; var t = ...

Performing a POST request using XMLHttpRequest with parameters in an asp.net environment

I am working on utilizing a javascript XMLHttpRequest object to send a post request to my action method. Here is my current setup: xmlhttp.open('POST', '../Employees1/HandleFileUpload', true); My action method does not currently take ...

How to Use Jquery to Delete a Specific String

I've been attempting to remove certain strings from a string using Jquery, however it seems like the code isn't working and my variable remains unchanged. var classes = $("body").attr('class'); alert('.side-nav' + classes); c ...

I am struggling to make the while loop in JavaScript stop even when I command it to

var dataStatus = '1'; while (dataStatus != 0) { $.ajax({ url: '/ajax.php?updateData='+dataStatus, dataType: 'json', async: false, success: function(response) { dataStatus = respo ...

Fill in according to the options selected in the dropdown menu

Recently delving into the world of React, I encountered a design challenge that needs solving. My goal is to have a selection field with various choice values, each offering different sets of KPIs and UOMs. Depending on the chosen value, I should be able t ...