The Angular directive is failing to acknowledge the attribute

Check out the following HTML:

<body ng-app="myCatApp">
        <div ng-controller="catagoryController">
            <add-remove-lister list="catagories"></add-remove-lister>
        </div>
    </body>

And here is the JS code:

    app.controller('catagoryController', ['catagoryList', '$scope', function(catagoryList, $scope) {
      $scope.catagories = catagoryList.catagoryList;
    }]);

    app.directive('addRemoveLister', [function () {
        return {
            scope: {
                list: '='
            },
template: function(tElement, tAttrs, scope) {
            templateHTML = '<ul>';
            var list = scope.list;
            for (o = 0; o < list.length; o++) {
                var curObject = scope.list[o];
                templateHTML +='<li ng-repeat="listItem in list"><button type="button" ng-hide="listItem.userSelected" ng-click="addToList()">Add</button>';
                templateHTML +='<button type="button" ng-hide="listItem.userSelected" ng-click="removeFromList()">Remove</button>{{listItem.text}}';
                for (var prop in curObject) {
                    if (curObject.hasOwnProperty(prop) && prop.constructor === Array) {
                        templateHTML += '<add-remove-lister list="listItem.'+ prop +'"></add-remove-lister>';
                    }
                }
                templateHTML += '</li>';
            }
            templateHTML += '<ul>';
            return templateHTML;
        }
        }
    }]);

Unfortunately, there seems to be an issue with the code. When debugging, I noticed that the "list" variable is showing up as just a string "catagories" instead of the actual object from the controller's scope...

Let me elaborate on my objective:

I am working on a directive that will generate a list from any given array. The requirements are: 1) All elements in the array must be objects containing properties {text : 'text', userSelected: 'bool'}

If the directive encounters an object within the list that has a property which is itself an array (containing objects with the aforementioned two properties), it should call itself recursively on that array.

In addition, the directive should display buttons next to each list item so users can modify the userSelected property of the object (to include them in their "options")

Answer №1

Give this a try for your template function

template: function(tElement, tAttrs, scope) {
        newTemplate = '<ul>';
        newTemplate +='<li ng-repeat="listItem in list"><button type="button" ng-hide="listItem.userSelected" ng-click="addToList()">Add</button>';
        newTemplate +='<button type="button" ng-hide="listItem.userSelected" ng-click="removeFromList()">Remove</button>{{listItem.text}}';
        newTemplate += '<add-remove-lister ng-repeat="(key, val) in listItem" ng-if="val.length" list="val"></add-remove-lister>';
        newTemplate += '</li>';
        newTemplate += '<ul>';
        return newTemplate;
}

Just keep in mind that it's likely you can achieve the same result with just a template, so the template function may not be necessary.

The main purpose of a template function is to allow manipulation of the original HTML DOM or to extract specific sections from the initial element for manual transclusion.

Furthermore, there seem to be some issues with your directive already (such as needing defined functions on your directive's scope in order to reference them in your template). Additionally, with an isolated scope, you cannot access functions from the parent scope without passing them in as attributes or using another method to add or remove elements.

For a demonstration, check out this Functional Plunk Example.

Answer №2

Various methods to access a list are available:

app.directive('addRemoveLister', [function () {
    return {
        restrict: 'E',
        scope: {
            list: '='
        },
        template: "test {{list}}",
        link: function (scope, element, attrs) {
          console.log(scope.list);
        },
        controller: function (scope) {
          console.log(scope.list);
        }
    }
});

Alternatively, you can compile your dynamic template during the linking phase:

app.directive('addRemoveLister', function ($compile) {
  var getTemplate = function(list) {
        var templateHTML = '<ul>';
        for (o = 0; o < list.length; o++) {
            var curObject = scope.list[o];
            templateHTML +='<li ng-repeat="listItem in list"><button type="button" ng-hide="listItem.userSelected" ng-click="addToList()">Add</button>';
            templateHTML +='<button type="button" ng-hide="listItem.userSelected" ng-click="removeFromList()">Remove</button>{{listItem.text}}';
            for (var prop in curObject) {
                if (curObject.hasOwnProperty(prop) && prop.constructor === Array) {
                    templateHTML += '<add-remove-lister list="listItem.'+ prop +'"></add-remove-lister>';
                }
            }
            templateHTML += '</li>';
        }
        templateHTML += '<ul>';
        return templateHTML;
  }

    return {
        restrict: 'E',
        scope: {
            list: '='
        },
        link: function(scope, element, attrs) {
            var el = $compile(getTemplate(scope.list))(scope);
            element.replaceWith(el);
        }
    };
});

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

Issues have been encountered with the functionality of the Bootstrap selectpicker library

I am working on a dropdown list forum and want to incorporate a search feature. I decided to implement the selectpicker library for this purpose, but I keep encountering an error in the console that says Uncaught TypeError: Cannot read properties of undefi ...

Encountering an issue with compiling Angular due to a Type Inference error

interface Course { name: string; lessonCount: number; } interface Named { name: string; } let named: Named = { name: 'Placeholder Name' }; let course: Course = { name: 'Developing Apps with Angular', lessonCount: 15 }; named = ...

What is the process to manually trigger hot reload in Flutter?

I am currently developing a Node.js application to make changes to Flutter code by inserting lines of code into it. My goal is to view these updates in real-time. Is there a way to implement hot reload so that every time I finish writing a line in the file ...

Is {{@index}} an even or odd number in Handlebars: A Step-by-Step Guide

I'm currently cycling through an array, and I'd like to adjust the background color of the div based on whether the current index is odd or even. Unfortunately, when I try to use {{@index}} within an if statement in Handlebars, like so: {{#each ...

Beautify JSON data display

My JSON object is displaying differently when I alert it: https://i.stack.imgur.com/lwNIJ.png I would like it to show like this instead: https://i.stack.imgur.com/cVakX.png function getEmployeeNameById(id){ return staffArray.find(item => item. ...

Tips for altering dual data values in Vue

When working with Vue.JS, I encounter the following situation: data() { return { name: 'John', sentence: "Hi, my name is {{ name }}", }; }, In my HTML file, I have the following line: <h2>{{ sentence}}</h2> ...

The typeof() operator in Javascript is providing unexpected results when checking the variable type

Hello, I have encountered an interesting issue while using console.log(typeof(variable) compared to console.log(variable). When I check the console, the variable appears to be an array of objects. However, when I use typeof, it shows as an object. I a ...

Dynamically updating the scroll area in Ionic using real-time data

Hello, I am currently working on an Ionic project and have created a code pen for it. At the moment, the code pen just displays an image with two buttons for zooming in and out. However, I have encountered an issue. When I click on zoom in and scroll to ...

Display a loading spinner dialog using Jquerymobile until the page finishes loading

I am facing an issue with my app where I need to show a Loading dialog while sending data from the first page to the server. The goal is to display the Loading dialog until the send operation (posting to server) is complete and then proceed to page two. I ...

Can JavaScript trigger an alert based on a CSS value?

Hello, I am facing an issue. I have created a blue box using HTML/CSS and now I want to use JavaScript to display an alert with the name of the color when the box is clicked. Below is my code: var clr = document.getElementById("box").style.background ...

What is the best way to show multiple markers using react-google-maps?

Can anyone help me figure out how to display multiple markers using the react-google-maps npm package? I've been following a demo that shows how to display one map marker, but when I try to add a second marker element, it doesn't show up on the m ...

The angular datepicker functionality seems to be malfunctioning

unique-example encountering this error message: error TS2307: Cannot find module 'mydatepicker' also encountering a compile time error at this line: import { MyDatePickerModule } from 'mydatepicker'; report.module.ts : import ...

Double Calling of Angular Subscription

I am currently working with a series of observables that operate in the following sequence: getStyles() --> getPrices() Whenever a config.id is present in the configs array, getStyles() retrieves a style Object for it. This style Object is then passed ...

How to change the image source using jQuery when hovering over a div and set its class to active?

I am working with a div structure that looks like this: <div class="row margin-bottom-20"> <div class="col-md-3 service-box-v1" id="div1"> <div><a href="#"><img src="path" id="img1" /></a></div> ...

Using AngularJS, deleting items by their $index with ng-repeat

I'm currently working with two directives: a query builder and a query row. The query builder directive utilizes ng repeat to display query rows from an array. While the add button functions properly, I am looking to add a delete button as well. Howev ...

Dealing with errors in AngularJS factory servicesTips for managing errors that occur

Factory code app.factory('abcFactory', function ($http, Config, $log) { var serviceURL = Config.baseURL + '/results'; return{ results:function() { var promise = $http({ method: 'GET&apos ...

The NoUiSlider had already been initialized

Currently, I am facing an issue when trying to incorporate noUiSlider with Angular JS. I have a directive that contains 4 sliders and I intend to display this directive on 2 different pages. However, each time I switch between the pages, an error occurs st ...

Determine the presence of a JSON object within a file using JavaScript

Currently, I am developing a mobile app using react-native and have been facing challenges implementing error checking. To store data retrieved from an API in JSON format, I am employing redux along with thunk. At times, the search results yield a JSON res ...

Ensure to verify the input's value by clicking the button

Upon clicking a button, I am trying to determine if there is any content in an input field. However, it seems that the check only happens once when the website first loads. Subsequent clicks of the button do not detect any new input values entered into the ...

JavaScript - continuously update the image marked as "active"

I have a collection of 4 pictures that I want to rotate through in my web application. Each picture should have the "active" class applied to it, similar to when you hover over an image. .active, .pic:hover{ position: absolute; border: 1px solid ...