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

What is the process for loading a script file from within a component's HTML?

My goal was to include a specific script file in the component html, but I noticed that when I added the script reference within the html itself, the inner script file was not rendered along with the component on the page. Component import { Component } ...

Using the spread operator in combination with the reduce function in JavaScript

I am attempting to generate all possible paths of the provided JSON object. I have managed to generate the paths, but I would like the final array to be flattened without any nested arrays inside it. I tried spreading the array, but there are still some ne ...

Tips for retrieving an input value following a DOM insertion

Developing a function to inject HTML into the DOM following an AJAX call like this: The function for injecting HTML $.ajax({ type: "POST", url: base_url + "main/GetTheLastSeq" }) .done(function( msg1 ) { ...

Retrieving the value of a child in JSON

I have encountered this JSON structure and I am interested in extracting the value of "resource_uri" which is "/api/v1/client/2/". My implementation revolves around Backbone/javascript. Unfortunately, using json['resource_uri'] does not produce ...

Alert for JavaScript Increment (++) Operation

While reviewing my code using jslint, I noticed a warning regarding the increment operator: var x = 1; x++; Warning: Unexpected expression '++' in statement position. According to the documentation: "They are second only to faulty archi ...

A guide on implementing the grid feature in Angular.js

Looking to add the following features in my Angular grid: Paging Filtering Column-wise sorting Can anyone recommend an Angular JS grid that supports these functionalities? ...

What happens when there is no match found while attempting to edit a form with the UI-Bootstrap typeahead directive?

Here is the code that demonstrates how my typeahead input box functions. Users can enter a name, and the relevant information will populate the rest of the form. If no match is found, users should still be able to input the name and related details into th ...

"Exploring the world of AngularJS Datepicker alongside the power

My desire is to have a calendar that displays only the option of selecting a month and year, with the format being displayed as "yyyy-mm". Once the month and year are selected, I need it to update the ng-model variable value in the specified format. I&apos ...

Utilizing timezones with Moment.js

Currently, I am utilizing momemt.js and moment-timezone.js to present time in the browser. At this time, I have received epoch time from the server which has been converted to central time. My goal now is to exhibit the time in EST/EDT format. To achieve t ...

Tips for adjusting HighCharts layout with highcharts-vue integrations

I have a fairly simple component: <template> <div> <chart v-if="!loading" ref="priceGraph" constructor-type="stockChart" :options="chartData" ...

Using Express middleware in a TypeScript Express application

I'm currently converting the backend of an ExpressJS application to Typescript. While working on the auth.routes.ts file, I encountered an issue with the middleware (authMiddleware). It seems like there might be a typing error, as the same code in the ...

Error in custom class using vanilla JavaScript: "Error: Unable to assign innerHTML to an undefined property"

Apologies for the ambiguous title, but I am struggling to pinpoint the exact issue at hand... I'm essentially guessing my way through this problem. This marks my initial venture into creating a reusable Javascript class. Below is a simplified version ...

Tips for integrating google's api.js file into my vue application

Currently, I am in the process of integrating Google Calendar into my Vue project. The steps I am following can be found at this link. Additionally, I came across an example code snippet at this URL. This is how my Vue file looks: <template> <d ...

Vue-router: the browser tries to open a <router-link> element as if it were a local file

Having some trouble with Vue-router - when I click on a navigation link, the desired component briefly displays before the browser tries to open it as a file. For instance, clicking on the "Badger!" link results in the browser attempting to open a local f ...

A plethora of unhandled DOMException errors found in a basic Vue.js application

I have been working on a Vue.js project for learning purposes, incorporating Quasar and Vuex. However, I keep encountering numerous Uncaught (in promise) DOMException errors which appear in the console. The application seems to work fine, but these red err ...

How to fetch React route parameters on the server-side aspect

I encountered a challenge while working with ReactJS and ExpressJS. The user uploads some information on the /info route using React and axios. Then, the user receives route parameters from the server side to redirect to: axios.post('/info', Som ...

Preventing User Input in Autocomplete TextField using React Material UI

Currently, I am utilizing the Material UI component Autocomplete to display options. However, I would like for Autocomplete to function more like a select dropdown, where users do not need to type anything to receive suggestions. Is there a way to modify A ...

`AngularFire services/factories that utilize nested models`

I am currently exploring how to nest models using factory-model/classes in combination with Firebase for data storage. For instance, imagine I am developing a task management app where Lists contain multiple Tasks, and each Task has various Details associa ...

What is the best way to get rid of a tooltip from a disabled button

I am facing an issue with my button that is disabled using ng-disabled. The problem is that the button still shows a tooltip even when it is disabled. I need to find a way to remove the tooltip when the button is disabled. Check out my Button ...

Utilize the fetch function to showcase information retrieved from a specific endpoint on a webpage using Javascript

Hey there, I have a Node server with an http://localhost:3000/community endpoint. When I make a GET request to this endpoint, it returns information about three different users in the form of JSON objects. [ { "avatar": "http://localhost:3000/avatars ...