Exploring the function of 'this' in object transmission to a modal

I am currently setting up a modal service as demonstrated in various instances such as here and here. I have come across the use of vm but do not completely grasp its purpose.

At line 13, there is the initialization of var vm = this; followed by usage of vm.. Does this action transform them into a model and expose them to the $scope?

In my attempt to pass an object to the modal that changes each time the modal is opened, I have previously achieved this by defining the object as a $scope variable.

The code used to open the modal is as follows:

$scope.openExercise = function(exercise) {
    $scope.activeExercise = exercise;
    myModals.openExercise(exercise)
        .then(function(result) {
            console.log()
        }, function(err) {
            alert(err);
        });
};

Upon using console.log, I can see my complete object; however, it does not show up in the modal where I intend to display it as {{exercise.name}}, etc.

My initial query pertains to the utilization of var vm = this;. Secondly, how can I bind/pass my object for it to be displayed in the modal?

Thank you in advance.

EDIT - Modal Code Added

<ion-content class="has-subheader has-footer" lazy-scroll delegate-handle="modalContent">
    <ion-slide-box ng-init="updateSlider()" ng-show="showimage" on-slide-changed="slideChanged(index)" class="exercise-slider-slides" does-continue="false" auto-play="false" show-pager="true">
        <ion-slide ng-repeat="sliderimage in activeExercise.images track by $index">
            <div ng-if="isNumber(sliderimage)" class="modalSliderThumbnail" style="background-image:url(http://.s3.amazonaws.com/medium/{{sliderimage}}.jpg)"></div>
            <div ng-if="!isNumber(sliderimage)" class="modalSliderThumbnail" style="background-image:url({{sliderimage}})"></div>
        </ion-slide>
    </ion-slide-box>
    <ion-list can-swipe="true" ng-hide="showimage">
        <form>
            <!--                 <label class="item item-input item-stacked-label">
                <span class="input-label energized">Title (Tap to edit)</span>
                <input type="text" class="title-input" placeholder="" initial-value ng-model="activeExercise.exerciseName"></input>
            </label> -->
            <label class="item item-input item-stacked-label">
                <span class="input-label energized">Description (Tap to edit)</span>
                <textarea placeholder="Tap to add a Description" initial-value ng-model="activeExercise.exerciseDescription"></textarea>
            </label>
        </form>
        <ion-item ng-click="showPopup()" class="item-icon-right param-button">
            <i class="icon ion-ios-plus-outline"></i> <span class="energized">Tap to add Variables</span>
        </ion-item>
        <ion-item ng-repeat="param in activeExercise.Params track by $index" ng-click="showPopup(param)">
            <strong>{{param.param}}</strong> : {{param.childParam}}
            <ion-option-button class="ion-minus-circled assertive button-options" ng-click="deleteParam(param)"></ion-option-button>
        </ion-item>
    </ion-list>
    <button class="button button-block button-gradient icon-right ion-ios-plus-outline add-to-programme-button" ng-click="addExerciseToProgramme(activeExercise, programme);showimage=true" ng-hide="showimage">Add to {{programme.programmeTitle}}</button>
</ion-content>

Answer №1

Using "vm = this" in your controller helps avoid scoping issues, especially with closures in nested functions. For example:

var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
    this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);

By setting vm to this at the beginning of your controller, you can safely reference your scope using vm even within inner functions where "this" may have a different meaning.

To provide an answer to your second question, please share the code of the modal's 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

Discovering the cities associated with a particular province in ReactJS

Hello, I'm new to reactjs and I am looking for a way to retrieve the cities of a province when it is passed as input. I have tried using npm but haven't had any success so far. Any help would be greatly appreciated. Thank you! ...

Switch between various API content upon clicking (JavaScript)

Upon receiving data from an API in JSON format using PHP, I aim to incorporate a filter mechanism for displaying distinct content sourced from the API. For instance, by specifying a filter in my API call, I can retrieve separate datasets such as one with ...

Converting units to rem dynamically in CSS: a comprehensive guide

Hey there, I'm currently trying to dynamically convert units into rem in CSS and facing some issues. I have set the root font-size as 23px The current font-size is 16px The expected result should be 16 / 23 => 0.695rem Question: I am looking for ...

Error: The function $(...) does not contain a progressbar

I encountered a TypeError saying $(...).progressbar is not a function when loading the Gentelella - Bootstrap Admin Template Page. This error is affecting many jQuery processes. How can I resolve this? Error in my Code: (custom.js) // Progressbar if ($( ...

Refresh an HTML page using Selenium WebDriver and Python without the need to actually refresh the entire

On a page with self-refreshing content (via WebSocket) similar to this example, the constantly changing content is not being detected by my Firefox webdriver. Although the new content is visible in the Firefox window, my webdriver only captures the initial ...

Initiate requests to external servers from a NodeJS backend

My NextJS application seamlessly collaborates with a NodeJS server to act as the front end of my innovative three-tier architecture. 'use client'; import FormControl from '@mui/material/FormControl'; import InputLabel from '@mui/m ...

Uncharted Territory: Exploring asynchronous loops with async await and Promise.race?

Currently, I am involved in a project that requires brute forcing a PDF password. To achieve this task, I am using PDF.js to verify the password and implementing promise.race to execute parallel functions for efficient performance. This is how I have str ...

Utilize anonymous functions to reassign the button click event - JQuery

I'm dealing with a situation where I have 5 HTML buttons, each with a click event listener attached to it in the form of an anonymous function. For example: $('#button1').click(function(){ //some code }); At a certain poin ...

Creating dynamic templates and embellishments in VUE

My VUE components, including Field and Form, are able to dynamically render a form based on the provided data. <template> <form @submit="$emit('submit', $event)" > <template v-for="(item, index) in form.elemen ...

Angular Resolution Verification

I'm currently working on making HTTP calls in Angular and I want to trigger a different service function if an error occurs. The problem is, no matter what the original service call function returns, the promise always ends up being "undefined". Here& ...

Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated. The current representation of individual's data ne ...

Struggling to remove an image while using the onmouseover event with a button?

I am encountering an issue with hiding an image using the onmouseover event not applied directly to it, but rather to a button element. The desired functionality is for the image to appear when the mouse hovers over and disappear when it moves away. Here&a ...

Having trouble rendering an object in my ThreeJS project. The error message says: "THREE.OBJLoader: Unexpected line: 'usemap glass'"

I encountered an error while running threejs in an angular 8 application. The objective is to load an object, for which the object and material files were obtained from Kenney assets. Despite referencing examples on the official threejs site and other onli ...

Node.js console and endpoint are returning an object, but the JSON object cannot be fetched

Currently, I am working on a project for an online course where I am utilizing an NLP sentiment analysis API. Although I have made significant progress, I seem to be stuck at the final step. When I send the URL for analysis via the API call, I can see the ...

Performing an Ajax POST request using jQuery

I am currently working on modifying my code to use POST instead of GET to send variables to a PHP page. The current code sends data via GET and receives it in JSON format. What changes should I make in order to pass the variables to process_parts.php usi ...

Request for removal in Express.js

Currently in the process of developing a MERN-stack app, but encountering issues with the delete request function. Here is the relevant code snippet: Upon attempting to send a delete request via Postman, an error message is displayed. I have researched ...

The error message "Angular Animate - TypeError: undefined is not a function" indicates that

I seem to be encountering an issue when loading my Angular App. "TypeError: undefined is not a function" After a bit of investigation, it appears that the problem lies in declaring ngAnimate in my controller and I noticed the error originating from the A ...

Update the value of a td element when a select option is changed in another td element within the same table row

I have a table set up as follows: Header1 | Header2 | Header3 | Header 4 | Header 5 Row 1 |<span>Some Text</span> | <select></select> Row 2 Row 3 . . . . Rows generated dynamically. My objecti ...

Is there a way to simultaneously redirect to a new page and trigger an event on that page?

As a programming novice and a newcomer to this community, I am seeking assistance with my query. I am interested in learning how to redirect from page 1 to page 2 and then immediately trigger an event on page 2. Below is the code snippet from page 1: & ...

The variable process.env.CLIENT_ID is functioning correctly within a function, but does not work when declared as a global

Trying to implement oAuth for Google API Using .env file to hide sensitive variables with .gitignore Facing an issue when trying to define the CLIENT_ID variable globally CLIENT_ID = process.env.CLIENT_ID When I run and log the variable outside of a fun ...