Trouble getting CSS and Javascript to bind when dynamically appending HTML elements

Attempting to dynamically bind HTML from an Angular controller

SkillsApp.controller('homeController', function ($scope, $http, $q, $timeout) {
$scope.getAllCategories = function () {
    $http({
        url: "/Categories/GetAllCategories",
        method: 'GET',
    }).success(function (response) {
        $scope.categoriesList = response;
        for (var i = 0; i < $scope.categoriesList.length; i++)
        {
            var categoryyy = '<li><a href="#" data-filter=".commercial">' + $scope.categoriesList[i].Name + '</a></li>';                
            $('#Category').append(categoryyy);
        }           

    });
};

HTML Result:

<ol class="type" id="Category">                                
   <li><a href="#" data-filter=".commercial">Commercial</a></li>
  <li><a href="#" data-filter=".residential">Residential</a></li>
  <li><a href="#" data-filter=".commercial">Commercial</a></li>
  </ol>

Target HTML:

 <div class="col-sm-6 col-md-4 col-lg-4 RESIDENTIAL">
  <div class="portfolio-item">
   <div class="hover-bg">
    <a href="img/portfolio/01-large.jpg" title="Project Title" data-lightbox-gallery="gallery1">
     <div class="hover-text">
       <h4>Project Name</h4>
     </div>
     <img src="~/img/portfolio/01-small.jpg" class="img-responsive" alt="Project Title">
   </a>
  </div>
  </div>
  </div>

The above code failed to bind to the target element.

The same code functions perfectly when static HTML code is used.

Seeking assistance in identifying where errors may exist within the code.

To be more specific : Issues with dynamic binding causing DOM not able to bind data-filter Is there a way to refresh DOM objects after dynamic HTML binding?

Answer №1

If you want to iterate through arrays, I suggest using the ng-repeat directive. Check out the ng-repeat documentation for more information.

AngularJS is different from Jquery. Take a look at this question to better understand how AngularJS functions.

In addition:
Have you set your app with ng-app="SkillsApp"?
Have you assigned your controller with ng-controller="homeController"?
Are you invoking getAllCategories() somewhere? For example: ng-init="getAllCategories()"

Example

SkillsApp.controller('homeController', function ($scope, $http, $q, $timeout) {
$scope.getAllCategories = function () {
    $http({
        url: "/Categories/GetAllCategories",
        method: 'GET',
    }).success(function (response) {
        $scope.categoriesList = response;
    });
};


<body ng-app="SkillsApp" ng-controller="homeController" ng-init="getAllCategories()" >
    <ol class="type"> 
        <li ng-repeat="categorie in categoriesList">
            <a href="#">{{categorie.name}}</a>
        </li>
    </ol>
</body>

Answer №2

Consider incorporating this snippet into your code:

$scope.categoriesList = [];

It is important to store data in an array within the $scope. Additionally, for a more organized approach, you may opt to utilize either a service or factory. For further information, refer to the LINK

Take a moment to compare and contrast the usage of service and factory within Angular. Cheers!

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

"Enhance your website with the dynamic duo of Dropzone

Currently, I am utilizing dropzone.js and loading it through ajax. I have assigned my menu ID as "#menu". The uploaded file should display in "#div1". Unfortunately, the callback function is not functioning properly. In an attempt to troubleshoot, I repl ...

Error: Trying to access the 'previous' property of an undefined value

I keep encountering an error with functions in firebase: TypeError: Cannot read property 'previous' of undefined at exports.sendNotifications.functions.database.ref.onWrite (/srv/index.js:5:19) at cloudFunction (/srv/node_modules/firebase-functi ...

How to position an absolute element beneath a fixed element

My website is experiencing a problem where the fixed header is overlapping an absolute paragraph on this page. Does anyone know how to resolve this issue? ...

How can I display a pre-existing div with a dropdown button?

I have individual div elements for each type of clothing item (shirt, pant, suit) that I want to display when the corresponding service is selected. This means that when I click on one of them, only that specific div will be shown. I am looking for a solut ...

When extracting information from a table within a Vue.js and Vuetify.js function

When trying to display a table, only one row is being printed. How can I resolve this issue? I have attempted various solutions (Vanilla JS worked). This project is for educational purposes and I am relatively new to JS and Vue.js. <template> < ...

The images in Bootstrap-Grid at 1920 resolution stay compact

Is there a way to make images grow beyond the 1280 resolution? This is how it appears at 1920 resolution https://i.sstatic.net/JmYc7.png And this is at 1280 resolution https://i.sstatic.net/Sk19K.png <div id="logokutu1" class="d ...

Pass the disabled select option value to a form using a hidden input field

My Django form has a section that is set up like this: <select {% if 'ba1' in widget.name or 'bs1' in widget.name or 'pm2' in widget.name %} disabled {% endif %} id="{{ widget.attrs.id }}" ...

The VisJS Network lacks proper alignment

I am attempting to generate a vis js network. This is how I envision the graph should appear https://i.sstatic.net/xIv3s.png Here is the code snippet extracted from the page source <script type="text/javascript"> var options = { ...

Issues with Next.js and Framer Motion

My component is throwing an error related to framer-motion. What could be causing this issue? Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function This error occurred during page generation. Any console logs will be ...

How can you hide all siblings following a button-wrapper and then bring them back into view by clicking on that same button?

On my webpage, I have implemented two buttons - "read more" and "read less", using a Page Builder in WordPress. The goal is to hide all elements on the page after the "Read More" button upon loading. When the button is clicked, the "Read More" button shoul ...

Navigating the Drift

I am a beginner in HTML/CSS and need some assistance. Here is the layout I am working with: <style> #main {background-color: red; width: 30%;} #right_al{float: right;} #to_scroll{overflow: scroll;} </style> <div id='main'> ...

There seems to be an issue with Select2 where the selected value is not

I have upgraded to version 4.0.0 full in order to take advantage of the features available in 3.5.2 as well. I am utilizing the query option to populate the results. The functionality is working properly, however, when I choose an item from the results, it ...

A warning has been issued: CommonsChunkPlugin will now only accept one argument

I am currently working on building my Angular application using webpack. To help me with this process, I found a useful link here. In order to configure webpack, I created a webpack.config.js file at the package.json level and added the line "bundle": "web ...

When using React, appending a React Link tag to an existing list item may result in the addition of two objects instead of the desired

Trying to create a loop that checks if an object's date matches with a date on a calendar. If it does, I want to add a React Link tag to the respective li element. The loop logic works well, but the issue is when appending the Link tag using createTex ...

JWT - Effective strategies for enhancing the user experience for a returning logged-in user

My client authentication system involves storing a JWT in `localStorage` once the user is verified. However, I'm not satisfied with the current user experience when a returning user is redirected straight to a new page without warning. window.locatio ...

Ensure that the image inside a resizable container maintains the correct aspect ratio

I often encounter a situation where I need to showcase a series of thumbnails/images that adhere to a specific aspect ratio within a flexible container. My current approach involves using a transparent, relatively positioned image to enforce the correct as ...

Searching for similar but not identical results using Knex.js

I am seeking a solution to retrieve similar posts without including the post itself. Here is my approach: export async function getSimilars(slug: string) { const excludeThis = await getBySlug(slug) const posts = await knex('posts') .whe ...

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...

The Safari 7.1+ browser seems to be having trouble with the spotlight effect

Why is the CodePen not functioning properly in Safari? Despite working well in Chrome and Firefox, it completely fails to work in Safari 7.1+. Can anyone provide some insights? http://codepen.io/cchambers/pen/Dyldj $(document).on("mousemove", function( ...

What is the best way to automatically close a modal window after pressing the submit button

Having some trouble with my modal window using pure CSS. Can't seem to get it to disappear after clicking the submit button. Any suggestions on how to hide it properly? Here is the code snippet of both the HTML and CSS for reference. Open to all ideas ...