One issue with AngularJs is that it does not accurately display data that has been modified within

My MediaService service is being modified within a component. The data in MediaService is connected to another component, but any changes made in the first component are not reflected in the HTML of the second component.

MediaService

angular
.module('commons')
.service('MediaService', function () {

    this.selectedMedia = {}
    this.isPlaying = false

    return this;

})

This is where the data is being altered

readerMedias

angular
.module("app")
.component("readerMedias", {
    bindings: {
        medias: "="
    },
    templateUrl: "app/reader/components/reader-medias/reader-medias.html",
    controller: function (MediaService) {
        MediaService.selectedMedia.url = "test" // using a real url
        MediaService.selectedMedia.type = "video" 
        MediaService.isPlaying = true
    }
})

The changes are seen in this component through debugging, however, they do not reflect in the component's HTML

readerPlayer

angular
.module('app')
.component('readerPlayer', {
    templateUrl: 'app/reader/components/reader-player/reader-player.html',
    controllerAs: '$ctrl',
    controller: function (MediaService, $scope){
        $scope.MediaService = MediaService
        console.log(MediaService)
        return this;
    }
})

readerPlayer HTML

div.playing-media(
    ng-draggable
    ng-init="$ctrl.isFull = true"
    ng-class="{\
        'full-media': $ctrl.isFull, \
        'min-media': !$ctrl.isFull \
    }"
    ng-if="MediaService.isPlaying"
)
    div.playing-head
        div
            span.material-icons.full(
                ng-click="$ctrl.isFull = !$ctrl.isFull"
            ) photo_size_select_large
        span.material-icons.close(
            ng-click="MediaService.isPlaying = false"
        ) clear

    div.content
        video(
            controls
            ng-if="MediaService.selectedMedia.type != audio"
        )
            source(
                ng-src="{{MediaService.selectedMedia.url}}"
                type="video/mp4"
            )

        audio(
            ng-if="MediaService.selectedMedia.type == audio"
        )
            source(
                ng-src="{{MediaService.selectedMedia.url}}"
                type="audio/mp3"
            )

Answer №1

Remove the return statement from the service:

angular
.module('commons')
.service('MediaService', function () {

    this.selectedMedia = {}
    this.isPlaying = false

    //Omit the return statement   

    //OR

    return this;    
})

In the absence of a return statement, the constructor will automatically return the this object created by using the new operator.


Ensure that the string has quotes:

div.content
    video(
        controls
        ng-if="MediaService.selectedMedia.type !=  'audio'"
    )
        source(
            ng-src="{{MediaService.selectedMedia.url}}"
            type="video/mp4"
        )

    audio(
        ng-if="MediaService.selectedMedia.type == 'audio'"
    )
        source(
            ng-src="{{MediaService.selectedMedia.url}}"
            type="audio/mp3"
        )

Not including quotes in the comparison causes the media type to be compared to $scope.audio which is undefined.

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

What is the best way to loop through JSON properties and then assign their values to elements within an array?

After searching for solutions similar to my goal, I have yet to find one that fits exactly what I need. JSON is still new to me, so any guidance is welcome. In my ASP.NET MVC 5 application, the Web API controller returns the following JSON: { "id": ...

Passing Optional Parameters to AngularJS Modal

Is there a way to pass an optional parameter to my angularJS modal? Let's take a look at the code: TRIGGER CONTROLLER: $modal.open({ templateUrl: 'UploadPartial.html', controller: 'photos.uploadCtrl', resolve: { presele ...

Using the jquery slider in conjunction with the onchange event

I have integrated a jquery slider add-on into my project that updates a value in a Linux file whenever it is manipulated. The slider is connected to a text input box, which is set as readonly and therefore always blurred. The issue I am facing is that the ...

Troubleshooting AngularJS: Directive unable to access controller's variable within scope

I am facing a challenge with an element that has both a controller and a directive featuring an isolate scope: scope: { dirVar: '= ' } My objective is to execute specific parts of the directive only when a certain variable is true. I am try ...

transmit data retrieved from `getStaticProps` to other static pages in NextJS

While working on my project, I encountered the task of fetching a large JSON dataset from an external API within the getStaticProps function. This dataset needs to be divided into multiple parts and passed as props to numerous static pages (potentially hun ...

What is the best way to format a string into a specific pattern within an Angular application

In my Angular component, I have 4 fields: customerName, startDate, and startTime. Additionally, I have a fourth field that is a textarea where the user can see the message that will be sent via email or SMS. Within my component, I have defined a string as ...

What methods do Google and Yahoo use to update the URL displayed in the browser's status bar?

Have you ever noticed that on Google and Yahoo search pages, the URLs of the search result links actually point to google.com or yahoo.com? It's a clever trick they use by adding extra arguments to the URLs that allow for redirection to the actual sea ...

What is the best way to retrieve information in an autosuggest textbox from a server or database?

I am looking for a way to modify my autosuggest textbox to fetch data from a server instead of a defined array. Can anyone provide guidance on how to achieve this? Here is the code snippet I am currently working with: HTML code- <!doctype html> &l ...

Ways to verify whether the checkboxes within a gridview have been selected

enter code hereMy Gridview has five checkboxes in each row with options 'NO', 'YES', 'NA', 'NA/U', and 'REPEAT'. I am looking to enable a button if any of the checkboxes among 'NO', 'YES&apos ...

Attempting to discover the secret to keeping a hamburger menu fixed in place once it has been expanded

Exploring this example https:// codepen.io/ducktectiveQuack/pen/mPGMRZ I had trouble understanding the code block, so I resorted to trickery (just remove the space between the '/' and the 'c' lol) My goal is to have the hamburger men ...

What steps should be taken to prepare data for transmission to a server in a Next.js environment?

I'm in the process of creating a website that requires authentication. I am using Next (React) and typescript for web development. My objective is to make most pages ServerSideRendered or StaticHTML. However, I encountered an issue right at the begin ...

`Issues encountered while converting PHP Array to JSON format`

I've been encountering difficulties converting a multidimensional PHP Array to JSON. While using json_encode, the result is null. I'm working on developing an orgChart where the data is extracted from a CSV file and stored in an array. The layou ...

Troubleshooting: jQuery addClass() function not functioning properly in conjunction with attr("href", something)

I am trying to implement a unique feature for a link using a Bootstrap button, where it only works on the second click. On the first click, the appearance of the link should change slightly. To achieve this, I am utilizing the .addClass(newClass), .removeC ...

Initiate an API request to the controller method in ASP.NET MVC using AngularJS

Hey there! I have a server-side controller method: public class CustomerController : ApiController { public void Remove(IList clients) { // perform remove action here.... } } I am currently working with AngularJS. Can someone pleas ...

NestJS Logger: Issue setting logger types in main.ts

When attempting to specify logger types in main.ts as illustrated in the official documentation: const app = await NestFactory.create(ApplicationModule, { logger: ['error', 'warn'], }); await app.listen(3000); I am encountering an i ...

Unveiling the secret to accessing properties using v-if within a custom component template relocation

I'm currently working on an application that reveals a hidden div when the text "Create Test" is clicked. Everything works well when the code isn't placed inside the template of a component. This seems strange to me, what could be causing this is ...

Tips for refreshing a table component after receiving a notification from a WebSocket in React JS

Currently, I am utilizing React table to load a page that shows a table with data fetched from an API. Additionally, I am listening on a web socket and whenever there is new data sent over the web socket, a console message is printed. My goal now is to a ...

Deciphering a JSON Array in JavaScript to extract specific components

I have a brief snippet for a JSON array and a JavaScript function that currently returns a single argument: <!DOCTYPE html> <html> <body> <h2>JSON Array Test</h2> <p id="outputid"></p> <script> var arrayi ...

Error ER_NO_REFERENCED_ROW_2 occurred while attempting to use the function LAST_INSERT_ID

As a newcomer to Vue.js and Express, I've been trying to figure out how to transfer the GuestID from the Guest Table to the foreign key GuestID in my reservations table. app.post('/create',(req,res,next)=>{ var mysql = require(' ...

Display a dynamic variable within React's HTML code

const fetchTime = () => { const currentDate = new Date(); const currentTime = currentDate + ' ' + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); return {currentTime}; } export default fun ...