How to attach functions to nested elements in an AngularJS directive

Being a newcomer to angularjs, I am facing difficulty in resolving this issue.

Custom Directive

app.directive('rating', [function () {
return {
    restrict: 'E',
    scope: {
        maxStars: '=',

    },


    link: function (scope, iElement, iAttrs) {
            scope.stars = [];
            for(var i=0;i<scope.maxStars;i++) {
                scope.stars.push(i);
            }

            iElement.bind('mouseenter', function(event) {

                scope.$apply(function(){
                    angular.forEach(iElement.children(),function(div){
                        angular.forEach(div.children,function(span){
                          span.addClass('rating-star-enabled'); //error addClass is not a function
                        });
                    });
                });
            });

    },
    templateUrl:'rating/rating.html'
};
}]);

Template of the Custom Directive

<div class="review-star">

   <span class="glyphicon glyphicon-record" ng-repeat="star in stars"></span>

</div>

Usage of Custom Directive

<rating max-stars="5"></rating>

I keep encountering the error "addClass is not a function." This issue persists with other functions as well, and when I log it in the console, all tags are being displayed correctly. What could be the cause of this error?

Answer №1

When looping through angular.forEach() on iElement.children(), you're actually iterating over a collection of raw DOM elements (hence why you should access them with div.children instead of div.children() within the nested angular.forEach()). It's crucial to convert span (which is also a raw DOM element) into a jqLite object before you can utilize addClass() method...

scope.$apply(function(){
    angular.forEach(iElement.children(),function(div){
        angular.forEach(div.children,function(span){
          angular.element(span).addClass('rating-star-enabled');
        });
    });
});

Answer №2

Did you attempt this method?

Utilizing angular.forEach to cycle through the children of the div, an error occurs when trying to add a class using the 'addClass' function.

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

In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead? var foundPeopleA = findPeopleA().then(function(result) { var res = [] result.map(function(el) { res.push(getProfileXML(el.sid)); ...

Customize the CloseIconButton in Material-UI Autocomplete for a unique touch

Hello everyone, I have a simple dilemma. I am trying to implement a custom closeIconButton, but the only available prop is closeIcon. However, this prop is not sufficient because I need this custom button to also have an onClick property. If I add the onC ...

Incorporating an HTML image into a div or table using jQuery

I am a beginner in using JQuery within Visual Studio 2013. My question is how to insert an img tag into a table or div using JQuery? For example, I have a div and I would like to generate an image dynamically using JQuery. Or, I have a dynamically create ...

Choose markers from various JSON layers within a specified distance

I am looking to merge at least 2 JSON layers to allow all their markers to be searchable within a specified radius after clicking. There are two files defined in the code as follows: var url = "Peterborough.json"; var url2 = "Test.json"; The implementat ...

When attempting to download a file in AngularJS from an API REST, the file ends up becoming corrupted

I have created an Excel report using the REST API and sent it to the front-end (AngularJS). When I directly access the URL from the browser, everything works fine. However, when I try to download it from AngularJS, the file is downloaded but then cannot be ...

What are the different techniques for implementing React-Redux? Comparing Redux-thunk and Redux-Saga

My understanding of Redux is still quite hazy as I delve into various techniques and methods. I am curious to learn about other methods similar to redux-Thunk and redux-saga. Each utilizes distinct functions such as CreateSlice. I am interested to know w ...

Inspecting the Ace Editor within the onbeforeunload event handler to confirm any modifications

I'm attempting to utilize the $(window).on('beforeunload', function(){}); and editor.session.getUndoManager().isClean(); functions within the ace editor to detect whether a user has made modifications to a document without clicking the submi ...

How to use React MUI Checkbox to set the checked value as false

I'm encountering an issue with the React MUI - Checkbox component. On my site, I have a checkbox linked to a handler that targets a REST API endpoint. This endpoint sets a boolean flag for the user in the database on a POST request and returns the boo ...

Is it possible to modify the host header within an Angular app?

I'm experiencing a vulnerability issue and to resolve it, I need to utilize SERVER_NAME instead of the Host header. Is it possible to accomplish this using Angular? ...

Changing the Default Title Presentation in Magnific Popup Using Custom HTML Elements

When utilizing Magnific Popup to generate an image gallery with customized titles containing HTML content, I am facing a challenge. The popup consistently displays the default title attribute value instead of my specified custom title, despite attempts to ...

Images will only be displayed if the optional html parameter is included; otherwise, they will be hidden

In my parent component, there is an image displayed at a specific path (note: the image is already stored in my project). This path can optionally have additional parameters. If the For instance, The image is visible (image) when the HTML path is: ww ...

What is the best way to include attributes in an HTML element?

I've been researching how to dynamically add attributes to an HTML tag using jQuery. Consider the following initial HTML code: <input type="text" name="j_username" id="j_username" autocorrect="off" autocapitalize="off" style="background-image: lin ...

Fade out a component in Material UI/React by setting a timeout in the parent's useEffect hook for when it unmounts

Incorporating a fade out transition into my child component, <Welcome />, using Material UI's Fade component is my current goal. This transition should be triggered by two specific conditions: The timeout set in the useEffect function expires. ...

When using element(by.binding('...'),getText(), all the content within the element is retrieved, as opposed to just the element itself

Examining the outcome of {{price}} and {{getAdditionalKm}} in my AngularJS Application using Protractor. Here is a snippet of the HTML I aim to test: <h1>{{ price(distance, time, time_standing, airport) | currency }}</h1> <p>Detailed Pr ...

Having trouble loading JSON data into HTML using jQuery

I'm struggling to create a basic menu using data from a JSON file. I've been attempting to figure out the correct logic for days now, but I seem to have hit a dead end: Here's the approach I've taken: $.ajax({ url: 'data ...

Utilizing ngRepeat to build intricate rows within a table

I have a unique collection that appears as follows: { "10": {}, "12": { "20": { "value": 1, "id": 1, }, "100": { "value": 12, "id": 1, } }, "14": { "10 ...

I am seeking a solution to this error that occurs whenever I attempt to call a function using a button

Issue " _ctx.hello is not a function TypeError: _ctx.hello is not a function at onClick._cache.<computed>._cache.<computed> (webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/di ...

Using Javascript, you can create a function that can disable or enable a text link based on

Here is the code snippet showcasing CSS styles and HTML elements: CSS: .enableLink{ font-family:Verdana, Geneva, sans-serif; font-size:12px; color:#069; padding-right:20px; text-decoration:underline; cursor:pointer; } .disableLink{ display:none; fon ...

Unable to interact with web element using JavaScript

Struggling to find a solution for simulating a click on a button element on Outlook.com mobile website using JavaScript. Despite numerous attempts from online sources, the button remains unresponsive to clicks. An interesting discovery was made that the c ...

Securing page access for unlogged users using VueJS: A guide

As I continue to hone my skills in VueJs, I am experimenting with creating sample applications. Currently, I am working on a straightforward app that features a login page where users input their credentials to access their profile. However, I am strugglin ...