What is the best way to refresh my view after loading a new JavaScript file that is required to generate the correct HTML elements?

When I use $http.get() to retrieve my model $scope.workoutData, the object appears fine in the console.log(data) output. However, my view does not load as if it has received the model. Once the model is updated, I also need to trigger the owlCarousel() function which adds elements and classes to my HTML behind the scenes. I have attempted using $scope.$apply(); in the commented out sections.

 app.controller('calendarCtrl', ['$scope', '$http', function($scope, $http){

  //Hard coding like this works just fine when I remove the $http.get() request
  //$scope.workoutData = {"1969-12-31":[["14:50:15","1","8","135",null].... 

  angular.element(document).ready(function () {
    $http.get("php/getWorkoutData.php")
    .success(function(data) {
        console.log(data); // show that I have a proper object
        $scope.workoutData = data;
    });

    //$scope.$apply();
    var owl = $("#owl-demo");

    // This needs to run after the model updates
    owl.owlCarousel({
        itemsCustom : [
            [0, 2],
            [500, 3],
            [1000, 4],
            [1600, 5]
        ],
        navigation : true
    });
    //$scope.$apply();
  });
}]);

Below is my HTML:

            <div id="calendar" ng-controller="calendarCtrl">
                <div id="owl-demo" class="owl-carousel owl-theme">
                    <div class="item" ng-repeat="(date, figures) in workoutData">
                        <div class="scollHeader">
                            {{date}}
                        </div>
                        <div class="scrollBody">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Time</th>
                                        <th>Exercise</th>
                                        <th>Reps</th>
                                        <th>Weight</th>
                                        <th>Location</th>

                                    </tr>
                                </thead>
                                <tbody>
                                    <tr ng-repeat="set in figures">
                                        <td ng-repeat="dataPoint in set track by $index">{{dataPoint}}</td>

                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

However, when I hard code owlCalousel(), it changes the view to look like this:

https://i.sstatic.net/m1o1v.png

I am looking for ways to ensure my View updates properly. Any suggestions?

Answer №1

Have you considered moving the owl code into the success callback in this way?

$http.get("php/getWorkoutData.php")
.success(function(data) {
    console.log(data); // confirming proper object
    $scope.workoutData = data;

    // Ensure this runs after the model updates
    owl.owlCarousel({
      itemsCustom : [
        [0, 2],
        [500, 3],
        [1000, 4],
        [1600, 5]
      ],
      navigation : true
   });
});

Answer №2

For a dynamic carousel experience, consider utilizing the angular-owl-carousel library. This tool allows you to easily integrate an owl carousel into your website by using a directive that fetches data from a designated controller.

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

Unable to download and install jspdf version 1.5.3

Currently, I am facing an issue where I need to convert HTML to PDF using jspdf 1.5.2. However, I am encountering an error that says "Cannot read property 'charAt' of undefined" when trying to utilize html2canvas. When attempting to upgrade to j ...

Ways to avoid the browser from storing a JSON file in its cache

Hey there, I'm working on a project and running into some issues with caching. The problem I'm facing is that the browser keeps holding onto the json file containing save data even after I update it elsewhere. This means that the browser is readi ...

Unable to establish a websocket connection with either Amber or NPM, uncertain of the reason

Amber CLI (amberframework.org) - v0.11.3 Crystal 0.27.0 [c9d1eef8f] (2018-11-01) LLVM: 4.0.0 Default target: x86_64-unknown-linux-gnu npm 3.5.2 Attempting to incorporate sockets using Crystal Lang and Amber has hit a snag. Despite following the guidelines ...

The resize function triggers twice as many events with each window resize

While working on my website, I encountered a navigation issue when resizing the browser from desktop to mobile size. Initially, the mobile menu worked on load, as did the desktop navigation. However, after running a script with $(window).on('resize&ap ...

Creating HTML tags using Kotlin

Looking to generate HTML using Kotlin in the browser, I experimented with the Kotlinx library. However, I found that it lacks support for callbacks like the following: div { onclick = { event -> window.alert("Kotlin!") } } Are there an ...

Tips for transforming intricate JavaScript arrays into a unified array and iterating through to create a table

I need help combining two arrays that contain objects and reassigning the values in a standard format. Can anyone provide some guidance? Thank you. Here is my current situation: array1 = [{Apple: Ken, Orange: Mary, Melon: Tina, Strawberry: Jessica, Mango ...

Troubleshooting Angular Integration with Rails: Identifying and Fix

We have some hardcoded code that needs to be made dynamic: ng-form class="form-horizontal" name="genderForm"> <div data-fields=""> <div class="form-field-gender control-group form-field" data-field=""> <div class= ...

An error occurs when attempting to assign a value to a MUI file TextField

Struggling with setting the value of a MUI Textfield that has type="file" props, resulting in the following exception being thrown: Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable Interest ...

Node JS fails to return body content in POST request

Exploring Node JS for the first time and attempting to post data to a specific URL and retrieve it. Using Postman for this task, but encountering an issue where the response data is coming back as undefined despite receiving a 200 status code. Even after ...

Unveil as you scroll - ScrollMagic

I am working on a skill chart that dynamically fills when the document loads. I am exploring the possibility of using ScrollMagic to animate the chart filling as the user scrolls down. After trying various combinations of classes and pseudo-classes in the ...

The AJAX data variable fails to send to PHP script although $_POST is defined

I am at my wit's end with this problem. I am attempting to send a variable to a PHP script using AJAX, and although I can confirm that $_POST is set, the variable remains undefined. Oddly enough, I have used almost the same code in other instances an ...

AngularJS Scope 101: Understanding the relationship between parent and child scopes with models, both with and without the use of a 'dot'

Example WITHOUT 'period' http://jsfiddle.net/CmXaP/168/ <div ng-app="myapp"> <div ng-controller="parent"> Parent ctrl value: <input type="text" data-ng-model="name" /> <div ng-controller="child1"> ...

Troubleshooting: Issues with the functionality of AngularJS Material dialogs

I am facing an issue with displaying an Array of items in a dialog. Despite not receiving any errors, the output is not as expected. $scope.showDialog = function (ev) { $mdDialog.alert({ controller: 'DialogController', ...

The functionality of window.localStorage.removeItem seems to be malfunctioning when used within an $http

Currently, I am sending a post request to my web service and upon successful completion, I am attempting to remove a token from local storage. Here is the code snippet: $http.post("MyService/MyAction").success(function (res) { if ( ...

Pulling images into an array using AJAX

I am trying to create an array of all images in a specified image folder. After searching for similar questions on stackoverflow, I am now feeling a bit stuck. var folder = "images/"; $.ajax({ url: folder, success:function(data){ functi ...

What could be the reason for the Nextjs fetch request returning undefined data?

Here is the code snippet for my GET request in the API section: export default async (req, res) => { const { query: { className }, method } = req; switch (method) { case "GET": try { const classDetail = await Class.findO ...

JQuery function fails to execute upon first page load

I am currently facing a situation where I need to wait for a specific image to load before either swapping out its src or showing/hiding the next image. The desired outcome is to display a placeholder image (silhouette) until the main image loads, then hi ...

A step-by-step guide on accessing an expressjs endpoint from a static html file using Vercel

I am working on a basic app that consists of one server named /api/index.js and one file called index.html located at the root. In the index.js file, there is a route defined as app.get("/api/mystuff", () => {...}) The index.html file makes a request ...

Customizing the select2 plugin in jQuery - A user-friendly alternative for select boxes

I am currently seeking a method to personalize the appearance of the Select2 plugin within a project. Although I have reviewed the documentation, I was unable to locate specific instructions on how to modify the styling of the select box. Please refer to ...

Issue in Angular: Attempting to access properties of undefined (specifically 'CustomHeaderComponent')

I have encountered a persistent error message while working on a new component for my project. Despite double-checking the injection code and ensuring that the module and component export logic are correct, I am unable to pinpoint the issue. custom-header ...