Sharing information between controllers while being initiated using $rootScope.$emit

I've created a common module that includes a controller, component, and template to initialize the app and set up the base layout. Within this module, there is also a stateful component that makes an HTTP GET request during initialization to fetch a background image from an API. Once the promise is resolved, I use $rootScope.$emit to send an event back to the common controller containing the image URL so that it can dynamically set the background image of the app.

The issue I'm facing is that when I console log the event response inside the $rootScope.$on() function, I see the result. However, anywhere else within the controller (including inside $onInit() or elsewhere), I get no output.

Even more puzzling is that I can successfully render the event data in the Common controller's template – whether it's inside an input box using ng-model or a paragraph. But when I try to include it as part of my inline CSS or background-image directive, it doesn't work as expected. The directive only receives the URL up to the variable name () before cutting off abruptly.

Any suggestions on how to resolve this would be greatly appreciated!

Below is the component controller code:

function MovieDetailController(MovieService, $rootScope){

    var ctrl = this;
    
    ctrl.$onInit = function(){

        // Retrieve additional data
        MovieService.getAdditionalData(ctrl.movie.movie_id).then(function(response){
            ctrl.actors = response.credits.cast.splice(0, 6);
            ctrl.extras = response.videos.results.splice(0, 3);
            ctrl.similar = response.similar.results.splice(0,6);
            ctrl.backdrop = response.backdrop_path;
            $rootScope.$emit('backdropChange', ctrl.backdrop);
        });

    }

}

angular.module('components.movie').controller('MovieDetailController', MovieDetailController)

And here is the code for the Common Controller:

function CommonController($state, $rootScope){

    var ctrl = this;

    $rootScope.$on('backdropChange', function(event, data){
        ctrl.backdrop = data;
        console.log('Back drop is ' + ctrl.backdrop); // Successfully displays result
    });

    ctrl.$onInit = function(){
        console.log('On Init, Backdrop is ' + ctrl.backdrop); // Does not log any result
    }
}

angular.module('common').controller('CommonController', CommonController)

This is the HTML template for the Common Controller:

<header class="row" id="topnav">
    <topnav class="col-sm-12 p-3 d-inline-flex"></topnav>
</header>

<!-- Testing if data is rendered inside the input box and it is! -->
<div class="col-sm-12"><input type="text" name="" ng-model="$ctrl.backdrop"></div>

<!-- Directive only receives first part of URL up to variable then cuts off-->
<main class="row" id="main-body" back-img="https://image.tmdb.org/t/p/original{{$ctrl.backdrop}}">
    <aside class="flex-fixed-width-item bg-white" id="sidebar">
        <sidebar></sidebar>
    </aside>
    <section class="col" id="content-window">
        <!-- Filters and Main Section Submenu -->
        <div class="row">
            <nav class="col-sm-12 filter-container">
                <div ui-view="details-menu"></div>
            </nav>
        </div>
        <!-- Main Content Section -->
        <div ui-view="details" class=""></div>
    </section>
</main>

Lastly, here is the background image directive:

function backImg(){
    return {
        link: function(scope, element, attrs){
            var url = attrs.backImg;
            element.css({
                'background-image': 'url(' + url +')'
            });
        }
    }
}

angular.module('common').directive('backImg', backImg)

https://i.sstatic.net/U81D3.jpg

Answer №1

The backImg directive needs to use the $observe method on the specified attribute:

function backImg(){
    return {
        link: function(scope, element, attrs){
            attrs.$observe("backImg", function(url) {
                element.css({
                    'background-image': 'url(' + url +')'
                });
            });
        }
    }
}

According to the documentation:

$observe(key, fn);

Watches an interpolated attribute for changes.

The observer function will be called once during the next $digest cycle after compilation. It will continue to be called whenever the interpolated value is updated.

— AngularJS Attributes API Reference - $observe

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

Add Text to HTML and Delete Added Content Upon Button Click

I have successfully implemented code that appends new content to the div "users". However, I am facing an issue with removing the appended content when a user clicks a button. Currently, the code only removes the "remove" button upon clicking. But I need ...

Strategies for accessing a collection of DOM elements in React

Currently, I'm embarking on a challenge to complete 50 projects in 50 days by Brad Traversy. However, I've decided to take it up a notch by building them in Next.js with React since that's what I work with professionally. Unfortunately, thi ...

Top recommendation for showcasing a numerical figure with precision to two decimal points

Within my function, I am tasked with returning a string that includes a decimal number. If the number is whole, I simply return it as is along with additional strings. However, if it's not whole, I include the number along with the string up to 2 deci ...

In C#, how can the HTMLAgilityPack be utilized to extract a value from within a script tag?

I'm currently working with HTMLAgilityPack and I need to extract a value from a script tag. Here is the code: <div id="frmSeller" method="post" name="frmSeller"> <div class="clear"></div> <script type="text/javascript" language=" ...

I'm having trouble getting NextJS dynamic routes to function properly on my local server

src/app/user/[username].js [username].js content: import { useRouter } from 'next/router' export default function User() { const router = useRouter() return ( <p> {router.query.username} </p> ); } Upon visiting ...

Stop the erasure of an Array when navigating in Angular.js

I am facing an issue with the $interval service and Routing in Angular.js. I want to navigate between pages without losing the data present on the previous page. Let me clarify my situation. I am using the chart.js library to create a simple line chart. ...

How can refs be applied effectively in React applications?

I've been thinking about the role of refs in React and how they can address certain challenges for developers. However, I have found that the explanations provided in the React documentation are not very clear, and there seems to be a lack of helpful ...

JavaScript function for submitting form data using AJAX and performing validation

This is the code I have been working on: $(function () { $('.contact-form').submit(function (event) { $(this).find("input , textarea").each(function () { var input = $(this); if (input.val() == "") { ...

Retrieving binary content from an HTML5 Canvas using base64 encoding (readAsBinaryString)

Is it possible to extract binary data from an HTML Canvas? Currently, I have the following HTML code displaying an input file and a canvas below it: <p><button id="myButton" type="button">Get Image Content</button></p> <p>In ...

Leverage ajax/js to dynamically refresh a single select tag within a set of multiple

While working on a project, I encountered a challenge while using JavaScript to update a <select> tag within a page. The specific issue arises because the page is designed in a management style with multiple forms generated dynamically through PHP ba ...

What is the alternative way to achieve this functionality in Javascript without relying on jQuery?

I am encountering some dependencies issues with jQuery that are preventing me from using it. However, I still need to find a way to make this work without relying on jQuery libraries. Do you have any suggestions on how to achieve this? $(document).ready ...

Having trouble choosing options within Material UI's Autocomplete Component?

I'm having trouble selecting the options displayed in MUI's autocomplete component. It seems that using renderOption is causing this issue. I want to show an image along with the title in the component options, but without using renderOption, I h ...

typescript: best practices for typing key and value parameters in the forEach loop of Object.entries()

I have a specific object with key/value pairs that I need to iterate over using the entries() method of Object followed by a forEach() method of Array. However, I'm struggling to understand how to avoid a typescript error in this situation: type objTy ...

Guide on developing and releasing a Vuejs component on NPM

I have been diving deep into vue lately and incorporating it into all of the projects at my workplace. As a result, I have developed various components, particularly autocomplete. Although there are plenty of existing options out there, none seem to fulfil ...

Using Sequelize to Include Model Without Specifying Table Name

I am new to Sequelize I am facing an issue with "Nested Eager Loading" I have 2 tables with a one-to-many relationship Comment Table User Table This is the code I am using for the query Comment.findAll({ include: [User] }) The result I got was ...

Tips for adding content to a textarea after making manual changes to its existing content

One issue I encountered is with capturing the enter key on an input field and appending it to a textarea. While this works initially, any edits made directly on the textarea seem to disrupt the functionality. How can this be resolved? I have tested this i ...

Ways to prioritize HTML5/CSS3 navigation menu above the content

I am attempting to position my navigation menu on top of the content. Despite using z-index and overflow = visible, the desired effect is not achieved. I want to avoid setting the position relative as it will push the content downwards. Simply put, I want ...

Encountering issues with integrating NPM package into Meteor.js

Having installed both the meteor-npm package and the crypto npm package, I encountered some issues while using it in Meteor. npm: updating npm dependencies -- crypto Despite seeing this output in the console, when trying to use the npm package on the ser ...

Angular2 Service Failing to Return Expected Value

It's frustrating that my services are not functioning properly. Despite spending the last two days scouring Stack Overflow for solutions, I haven't been able to find a solution that matches my specific issue. Here is a snippet of my Service.ts c ...

Unravel the base64 encoded message from JavaScript and process it in Python

I'm currently facing an issue in Python while trying to decode a string sent by jQuery. Although I am not encountering any errors, I receive an encoding error when attempting to open the file. My objective is to decode the string in order to save it ...