CSS animation featuring dynamic source path

Trying to create an image with a dynamic path led me to the common solution of using

 document.getElementById();

However, I encountered a problem - my controller was being called before the HTML was fully loaded, resulting in an error because the id was referencing nothing. Understanding the issue, I explored potential solutions:

1) Placing the script within a

 <script> 

tag at the bottom of the page. While this method could work, I needed to call getElementById() in my controller to dynamically set the path based on parameters (specifically within a uibmodal controller).

Since passing parameters from the controller to the script tag in my HTML proved challenging, this approach no longer seemed viable.

2) I also attempted using window.onload(), but found that the function was not being triggered at all. Additionally, even when it did execute, it was too late for the image to be used in an animation.

At a loss for further solutions and working within an Angular environment, I refrained from exploring JQuery-based options, believing them to be no more effective than window.onload.

Seeking assistance in resolving this issue, I am sharing a snippet of my code below:

(function() {
    'use strict';

    angular
        .module('objectifDtyApp')
        .controller('MyBadgeController', MyBadgeController);

            MyBadgeController.$inject = ['$uibModalInstance', '$state', '$stateParams', 'BadgeView', 'items', 'Lesson'];

            function MyBadgeController($uibModalInstance, $state, $stateParams, BadgeView, items, Lesson) {
            var vm = this;

            console.log(items);

            vm.blocName = items.title;
            vm.ImagePath = items.path;
            console.log(vm.ImagePath);

            window.onload = function(){
                console.log("called");
                var img = document.getElementById('ImgBadge');
                img1.src= vm.ImagePath;

            };

            function clear () {
                $uibModalInstance.dismiss('cancel');
            }

             vm.close = function() {

             $uibModalInstance.close(true);
             //$state.go('viewCourse', {id: $stateParams.idLesson});
             }
         }
    })();
    
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div>
      <div class="Badge_logo-demo">
          <img ng-click="vm.close()" src="" alt="Badge_logo" id= "ImgBadge" class="Badge_logo">
          <h2 class="Badge_byline" id="Badge_byline"> You successfully did the Block {{vm.blocName}} </h2>

       </div>
     </div>

Given the inability of the current setup to yield results, I must stress that everything is initiated upon opening the uibmodal. Moreover, the {{blocName}} parameter functions correctly for me.

Answer №1

One way to dynamically update the src of your js files, images, or css is through angular scope.

Here's an example from my own application, specifically for css:

<link data-ng-if="brand" rel="stylesheet" type="text/css" data-ng-href="css/app/brand/{{brand.type}}/brand.css" />

In the controller, we have a property like this:

$scope.brand = {type: "cocacola"}

We then allow users to change that property by using a dropdown with ng-model="brand.type"

Take note of data-ng-if="brand", which checks if the property has been loaded by the controller yet. The benefit here is you can achieve this without resorting to basic JavaScript, leveraging Angular instead.

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

Script malfunctioning following an AJAX request

My page consists of a header where all my javascript is located. Within the body of the page, there is a link that triggers an ajax http request using vanilla JavaScript (not jQuery). This request retrieves a PHP form and injects it onto my page. The PHP ...

Update the row striping pattern once an element has been removed

I've been working on creating a todo-list and implemented row striping. Everything was going smoothly until I realized that when I delete a task, the row striping does not update as intended. Instead of changing to white, white, beige after a deletion ...

The strict-origin-when-cross-origin policy is enforced when submitting a POST request through a form to a specific route

Currently, I am diving into the world of Node.js, express, and MongoDB by reading Greg Lims's book. However, I've hit a roadblock when trying to utilize a form to submit data to a route that should then output the body.title of the form in the co ...

Integrating draw2d into Mean.js: A Step-by-Step Guide

I'm new to the MEAN Stack and I'm having trouble with something that seems pretty basic. My issue is trying to inject a new instance of draw2d from their downloadable library. The error message I keep receiving is: "Uncaught Error: [$injector: ...

jQuery unable to target Bootstrap button

I've been experiencing some trouble trying to attach a listener to a button I made with Bootstrap. <button type="button" id="buttonone" class="btn btn-default btn-lg good"> <span class="glyphicon glyphicon-minus" aria-hidden="true">< ...

The attempt to load a JavaScript resource has resulted in an error: the file was not located, despite the fact that it is a

Recently, I came across a new challenge in my application. Whenever I navigate to specific pages, I notice an error message in the development console: inject.preload.js:373 GET blob:http://my-app-name.test/ba65127c-383e-45b7-8159-9b52ea288658 0 () Upon ...

Text centered on hover for figure caption

Check out this fiddle http://jsfiddle.net/sLdhsbou/ where I am trying to center the "x" that appears on hover perfectly no matter what size the image is. Also, why does the transition not occur when moving the mouse outside of the figure, unlike when movi ...

Traversing a nested array in JavaScript to create a nested object in a loop

Struggling with translating a depth list into a nested object. Consider this list: "depth": [ 0, 1, 2, 3, 3, 2, 3, 3, 3 ], I'm trying to create a recursive function that generates an object like this: "depth": [ { "t ...

Managing and comparing category IDs in JavaScript to effectively store and render subcategories

My goal is to set the current category ID in a variable, and if the category changes, I want to store that as well. Then, I need to compare both IDs. If they are not equal, I want to set the subcategory to null. However, I am unsure of where my mistake lie ...

What is the best way to transition an absolute positioned element from right to center?

When hovering over an overlay element, I want the <h3> tag to appear with a transition effect from right to center, similar to the example shown here. Could someone please assist me in achieving this? Thank you in advance. HTML <div class="row m ...

Unable to incorporate values into ng-model

Is there a way to get the code in ng-model to function properly so I can display both the first and last names? Essentially, what I am trying to achieve is to transform this: {{currentInventory.assigned.first_name + ' ' + currentInventory.assig ...

Would you like to learn how to dynamically alter a button's color upon clicking it and revert it back to its original color upon clicking it again?

My Upvote button starts off transparent, but when I click on it, the background color changes to green. What I need is for the button to become transparent again when clicked a second time. I've attempted using the following code snippet: function ...

Generate a link that can easily be shared after the content has loaded using

One feature on my website involves a content container that displays different information based on which list item is clicked (such as news, videos, blogs, etc.). This functionality is achieved by using jQuery's load method to bring in html snippets ...

The loading spinner fails to function when triggered by the ng-click or ng-change events in an AngularJS application

I have implemented a loading spinner to display while the page is loading. App.controller('MailFolderController', ['$scope', '$http',function ($scope, $http){ $scope.loading = true; $scope.allotmentStatus = [ {"value ...

Using Angular to swap out the component's selector with HTML code

Consider the following component: @Component({ selector: 'passport-cell', templateUrl: './passport-cell.component.html', styleUrls: ['./passport-cell.component.scss'] }) export class PassportCell { @Input() public la ...

how to enable drag and drop functionality based on names in angularjs

In my project using angular js, I have implemented a drag and drop feature that allows items to be dragged between cells in two directions. I now want to enhance this functionality by allowing members with 'a's (e.g. 1a, 2a, etc.) to be dragged ...

Unlocking the Potential: Effective State Validation with Angular UI-Router

We're currently utilizing angular-ui-router (version 0.2.10, if I'm not mistaken). There exist two primary approaches for reaching a state: a) When a user manually enters or modifies the URL to correspond with a particular state. b) When cod ...

Comment sections that refresh automatically after being posted

I am determined to provide a clear explanation. Despite having some code, I am uncertain about how to make it clone comments and add new ones with user inputted text. Below is the snippet of code I am struggling with: <!DOCTYPE html> <!-- this i ...

The functionality of one button triggering the opening of two dropdown menus simultaneously is being successfully implemented

My issue is that I have created two different dropdowns, but they both open the same dropdown menu. Here is my code; <div class="d-flex"> <button class="btn btn-icon btn-group-nav shadow-sm btn-secondary dropdown-toggle" type="butto ...

Can browser javascript effectively prevent XSS attacks?

Is there a way to mitigate XSS attacks from browsers? I have an interesting scenario where I do not rely on cookies for authentication. Instead, I use http token headers sent via JavaScript Ajax. It is possible to secure these headers using closures: var ...