Injecting classes on the fly within an ng-repeat loop

Struggling with an issue in Angular as a newcomer. I'm utilizing masonry to create a dynamic assortment of images and videos in an ng-repeat and want to randomize the sizing classes for images. For instance, if an item in the ng-repeat is an image, apply one of two classes to it.

This is what I have so far for the template:

<div class="modalVid" ng-repeat="m in mediaList | filter:mediaType track by $index">
<a ng-if="m.type=='video'" zf-open="basicModal_{{$index}}" class="grid-item grid-item--video" ng-click="modalOpen()" style="background-image: url({{m.thumb}}); background-size: cover; background-repeat:no-repeat;"></a>
<a ng-if="m.type=='image'" zf-open="basicModal_{{$index}}" ng-class="grid-item" random-class ng-click="modalOpen()" style="background-image: url({{m.thumb}}); background-size: cover; background-repeat:no-repeat;"></a>
    <div ng-if="m.type=='video'"  class="" zf-modal="" id="basicModal_{{$index}}">
        <iframe width="560" height="315" ng-src="{{iFrameSrc(v.videoid)}}" frameborder="0" allowfullscreen></iframe>
    </div>
    <div ng-if="m.type=='image'" zf-modal="" class="large" id="basicModal_{{$index}}">
        <img src="{{m.screenshot}}">
    </div> 

I'm using a directive named random-class to add the class:

angular.module('mfApp')
.directive('randomClass', randomClass);

function randomClass(){

    return {
    restrict: 'AE',
    require:'^mfMason',
    link: function(scope, elem, attrs){

            var classArr = ['grid-item--width2 grid-item--height2', 'grid-item--width1 grid-item--height1'];
            var newClass = classArr[Math.floor(Math.random() * classArr.length)];

            elem.addClass(newClass);


    }
    }

}

And the masonry wrapper itself is a directive:

angular.module('mfApp')
.directive('mfMason', mfMason);

function mfMason(){
    return{
    restrict: 'AE',
    transclude:true,
    templateUrl: 'templates/masonry_build.html',
    controller:function($scope){
        $scope.classes = ['grid-item--width2 grid-item--height2', 'grid-item--width1 grid-item--height1'];
    },
    link: function(scope, elem, attr){
        var $grid = $('.grid').imagesLoaded(function(){
        $grid.isotope({
          itemSelector: '.grid-item',
          columnWidth: 182,
          gutter:1
        });
        });


      }
    };
}

Unfortunately, the code is not functioning correctly. I've attempted implementing solutions from other sources, like dynamically adding directives in ng-repeat, but haven't had success. I know there's still much about Angular, especially regarding directives, that I don't grasp fully, so any assistance would be greatly valued. Thank you!

Answer №1

require:'^mfMason' is searching for a controller named mfMason, but you have a directive with the same name. Try removing the require:'^mfMason', from your randomClass directive and check if that resolves the issue.

It's surprising that no error was being displayed in the console regarding this.

Update Here is a JSFiddle example showing that it functions correctly. I adjusted the width of the <div>s and added borders to make it easier to inspect using Chrome dev tools. I also displayed the output of the class attribute after adding your classes randomly.

Below is the javascript code:

angular.module('app', [])
    .directive('randomClass', function() {
        return {
            restrict: 'AE',
            link: function(scope, element, attrs) {
                var classArr = ['grid-item--width2 grid-item--height2', 'grid-item--width1 grid-item--height1'];
                var newClass = classArr[Math.floor(Math.random() * classArr.length)];
                element.addClass(newClass);
                element.text(element.attr('class'));
            }
        }
    });

And here's the html code:

<div ng-app="app">
    <div random-class class="something" style="border: 1px solid black; height:100px; width:300px;"></div>
    <div random-class class="something" style="border: 1px solid black; height:100px; width:300px;"></div>
    <div random-class class="something" style="border: 1px solid black; height:100px; width:300px;"></div>
    <div random-class class="something" style="border: 1px solid black; height:100px; width:300px;"></div>
    <div random-class class="something" style="border: 1px solid black; height:100px; width:300px;"></div>
    <div random-class class="something" style="border: 1px solid black; height:100px; width:300px;"></div>
</div>

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

Imitating a chain of promises function

While working on writing a test case for an Angular controller, I encountered an issue with mocking a service API call. The api call in my controller looks like this: this.testMe = User.getDetails().then(function (response) { this.user = resp ...

When CSS media queries are applied, the background color of Div does not fully extend to the edge

Although the problem seems simple, I am finding it difficult to find a solution. This page was created as part of my course. https://i.sstatic.net/DKCva.jpg While in developer mode and trying to resize the screen, I noticed that the background color of ...

Invoke the function functionA within the ClassComponentA class in the file fileA, located within the functionComponentA file of a REACT 17 application

My dilemma involves working with two components: a class component and a function component. I am trying to find a way to call a method from functionComponentA, which is located in classComponentA. Currently, I am achieving this by passing the method as pr ...

Forgetting your password with React JS

On my login page, there is a button labeled "Forget my password". When I click on this button, I want to be taken directly to the correct page for resetting my password. Currently, when I click on "forget my password", it displays beneath the login sectio ...

What is the best way to retrieve a value from a deeply nested callback function?

I am currently using the mssql npm library and it's functioning well. However, I'm facing difficulty retrieving the recordset returned from the sub-level callback function. Could someone guide me on how to obtain the recordset when dealing with ...

Unexpected values being captured by Request.Form from Dynamic Textboxes

I am currently working with dynamic text boxes and retrieving their values in the code behind file. These text boxes are created using Javascript on my ASP.NET page. Here is a snippet of my code: <script type="text/javascript"> $(docume ...

Enhancing react-input-range with unique Custom Arrow heads

I'm currently working with react-input-range to create a price range slider. While I've managed to customize the CSS of the range slider, I now need to figure out how to add arrow heads inside the circles as shown below: https://i.sstatic.net/pm ...

Angular's ngOnDestroy lifecycle hook does not execute as expected after a button click event

When working on my HTML code, I encountered the following: <div class="form-group"> <button type="submit" value="submit" class="btn btn-secondary btn-float">Upload</butt ...

I encountered some problems with conflicting Angular dependencies, so I decided to delete the node_modules folder

An error has occurred: The module 'H:\All_Files\Scripts\Angular\example\node_modules\source-map\source-map.js' could not be found. Please ensure that the package.json file contains a correct "main" entry. ...

What is the mechanism that guides a reverse while loop to determine its endpoint in JavaScript?

Lately in my exploration of JavaScript, I've discovered that reverse while loops are more efficient. They are often written in this manner: var i = someArray.length; while (i--) { console.log(someArray[i]); } I decided to test it out and noticed ...

Using Selenium Webdriver with C# to dynamically expand a RadMenu Webelement in Javascript

I am currently working with Selenium WebDriver in C# and facing an issue with a RadMenu. My goal is to hover over the menu so that it expands a sub menu, where I can find a specific webelement to click. I have tried using JavaScript for this purpose, but u ...

Is there a way to dynamically load a JSON configuration during runtime within a React application?

I am working on a React app that includes static content and does not use Node.js. I am in need of loading a configuration file in JSON format during runtime. The configuration file must be loaded in runtime because it needs to contain different data depe ...

Ways to modify, delete, or insert data elements within a collection of values using React

I'm currently working on implementing a dropdown menu for departments within a location edit form. I'm wondering if there's a way to update or create new elements in the list of values. The API I'm using only sends specific data elemen ...

What is the best way to ensure that DOM changes made in the success function are retained during a jQuery.Ajax() request?

After making a call to a webMethod, I receive a JSON object and use its attributes to populate some textBox values. However, I am facing an issue where the textBoxes are briefly populated but then quickly become empty again. I'm wondering if I made a ...

When an image is clicked, I am attempting to access data from a Sharepoint list

In my Sharepoint list, there are three columns: Image, Title, and Description. I am using ajax to retrieve the items from the list. The images can be successfully retrieved, but my goal is to display the title and description of the clicked image when an ...

"Utilizing Angular: Implementing two search input fields with a shared search functionality

I am currently working on implementing two search inputs for a single table with one search function in Angular. The first input is intended to search within the "Name" column, while the second input is meant for the "Description" column. However, I have ...

I am encountering an issue with Angular where the following error message is displayed: "src/app/app.component.html:18:20 - error TS2339: Property 'DepScreen' does not exist on type 'AppComponent'"

This code snippet is from my app.component.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" ...

Unforeseen behavior in Ajax success callback

My unordered list contains a href link. Initially, only the welcome page is visible on page load. Upon clicking the list for the first time after page load, the desired results are displayed in the corresponding div as expected. The issue arises when swi ...

Trigger is not activated by dynamically created element

I am dealing with a block of code that is dynamic and looks like this. var li3 = document.createElement('li'); li3.classList.add("col-sm-3"); li3.classList.add("no_padding"); var inner = ""; inner = inner ...

How can I show the initial three digits and last three digits when using ngFor loop in Angular?

Greetings! I have a list of numbers as shown below: array = [1,2,3,4,5,6,7,8,9,10] By using *ngFor, I am displaying the numbers like this: <div *ngFor =" let data of array"> <p>{{data}}</p> </div> Now, instead of d ...