Bring in TypeScript property from an external scope into the current scope

I am encountering an issue with my TypeScript code. Inside the anonymous functions, I am unable to change the properties of the class because they are out of scope. Is there a way to pass them in so that they can be modified?

class PositionCtrl {


    //rectangles: Rectangle[];
    lat: number; long: number; rad: number;
    save() {
        alert("Settings Saved");
    }




    constructor(private $scope: ng.IScope) {

        var tempLat: number = this.lat = 20;
        var tempLong: number = this.long = 20;
        var rad: number = this.rad = 1000;

        var mapCanvas = document.getElementById('map-canvas');
        var mapOptions = {
            center: new google.maps.LatLng(Number(this.lat), Number(this.long)),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDoubleClickZoom: true
        }
        var map = new google.maps.Map(mapCanvas, mapOptions)


        function setRad(x) {
            this.$scope.position.rad = x;
        }
        var marker = new google.maps.Marker({
            map: map,
            position: new google.maps.LatLng(Number(this.lat), Number(this.long)),
            title: 'Some location'
        });

        var circle = new google.maps.Circle({
            map: map,
            radius: this.rad,
            fillColor: '#AA0000',
            clickable: false
        });


        circle.bindTo('center', marker, 'position');
    
        //Watches radius for changes
        $scope.$watch('position.rad', function () {


            circle.setRadius(Number(rad));
            circle.bindTo('center', marker, 'position');
            console.log("done");

        });
        //Watches lat and long for changes
        $scope.$watchGroup(['position.lat', 'position.long'], function () {


            //THIS IS OUT OF SCOPE
            marker.setPosition(new google.maps.LatLng(Number(this.lat), Number(this.long)));


            console.log("done");

        });


            
        //Click event
        google.maps.event.addListener(map = map, 'click', function (event) {
            marker.setPosition(event.latLng);
            $scope.$apply(function () {
              
              //THIS IS OUT OF SCOPE
                this.lat = event.latLng.lat();
                this.Long = event.latLng.lng();
            })
            var test: number = 0;
            console.log(tempLong);
            test = Number(rad);
            circle.setRadius(test);
            console.log(rad);
            console.log(circle.getRadius());
            circle.bindTo('center', marker, 'position');
        });



    }

} 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Answer №1

Employing an arrow function ((args) => body) is recommended to maintain the context of this:

   //Monitoring lat and long for changes
    $scope.$watchGroup(['position.lat', 'position.long'], () => {
        // Works fine
        marker.setPosition(new google.maps.LatLng(Number(this.lat), Number(this.long)));
    });

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

"Revealing the specific row and column of the selected element in each table when hovering over it

On my webpage, I have set up two tables positioned side by side like this: <!DOCTYPE html> <table> <tr> <td> <table> <tr><td>1</td><td>2& ...

When a URL is entered, information is not retrieved from the database

I have a simple app setup where the data (iPhones from the database) is fetched in the AppComponent itself. ngOnInit(): void { this.iphoneservice.fetchIphones(); } The fetchIphones method is located in my iPhoneService file and consists of 3 functio ...

Using resolve to preload data in Angular's $routeProvider initialization process

I am working on an AngularJS application and need to fetch data from a REST API before the controller initializes. I am using the "resolve" in my routeProvider and have injected the necessary value into the controller to ensure that the data is available. ...

Utilizing the enter key function for form submissions on lists in AngularJS

In my AngularJS project, I am working on an account details page where users can update their personal information. The interface allows for multiple phone numbers and email addresses to be added. Currently, the functionality works well with mouse input or ...

What is the best way to delete markers from a leaflet map?

I need to remove markers from my map. I am looking to create a function that will specifically clear a marker based on its ID. I am utilizing Leaflet for the map implementation. Here is my function: public clearMarkers(): void { for (var id in this. ...

Watching for changes to an element's visibility within the viewport and automatically scrolling it

I'm having trouble making the input scroll to .here when its value matches "1". Even though I tried using a button with a handle-click function and it worked. Please lend me a hand with this issue. <template> <button @click="scrollToV ...

Encountered a problem initializing Rangy.js on Internet Explorer

Currently, I am developing an angular application that utilizes textAngular along with rangy-core and rangy-selectionsaverestore. However, I am encountering some errors specifically on the latest version of Internet Explorer: Module 'WrappedSelection ...

Refreshing the information in the database table

Upon receiving data from the server using ajax, I populate this table: $.each(data, function(i, item) { $('#MyTable tbody').append("<tr>" +"<td>" +data[i].A+ "</td><td>" +data[i].B ...

Error message stating: "The 'MktoForms2' property is not recognized within the scope of 'Window & typeof globalThis'."

Encountering the following error message: (Property 'MktoForms2' does not exist on type 'Window & typeof globalThis') while working with react and typescript useEffect(() => { window.MktoForms2.loadForm("//app-sj11.marke ...

Tips for designing the microphone appearance on the Google Chrome speech input interface

Google Chrome features an input control for speech recognition. If you want to know how to use it, check out this link. I'm looking to enlarge the microphone icon and possibly use a customized image for it. Increasing the width and height of the inp ...

What is the method to obtain an object as the return value from a click function in JavaScript?

I would like to retrieve the cell value from a table by clicking on a button. I have already created a function called getDetail in JavaScript that is implemented on the button, but I am facing difficulty in returning the value from the function. <butto ...

What is the best way to implement a fade animation with nganimate when transitioning between routes in Angular ui-router?

.ng-leave { transition: 1s linear all; opacity: 1; } .ng-leave-active { opacity: 0; } The code above specifies a fade animation whenever the router changes routes from one page (page1.html) to another (page2.html). However, if you want to hav ...

Prevent time slots from being selected based on the current hour using JavaScript

I need to create a function that will disable previous timeslots based on the current hour. For example, if it is 1PM, I want all timeslots before 1PM to be disabled. Here is the HTML code: <div class=" col-sm-4 col-md-4 col-lg-4"> <md ...

Sass: Setting a maximum width relative to the parent element's width

I have a resizable container with two buttons inside, one of which has dynamic text. Within my scss file, I am aiming to implement a condition where if the width of the container is less than 200, then the max width of the dynamic button should be 135px, ...

This error message indicates that the certificate for Angular 13 has expired

After successfully installing Angular and verifying the version, I encountered an issue when attempting to run the command npm start. Despite multiple attempts at uninstalling and reinstalling everything, the problem persists. Running npm install also resu ...

Preventing data loss in an Ionic array - encountering issues with using this.array.push

When attempting to use the storage get method to fill the array storedArr = [], I encounter the error message .push is not a function: storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : []; The c ...

The function WebForm_DoCallback is not recognized

Encountering an error where WebForm_DoCallback is undefined. UPDATE WebForm_DoCallback("AccountPageControl1", "FileSave~" + fileName, CVFileSavedServerResponse, null, null, true); function CVFileSavedServerResponse(param, context) { } Why isn't ...

Switching between API requests through a live feed

Hey there: import Rx from 'rxjs'; function mockApi(endpoint, time, response) { return new Rx.Observable(observer => { console.log(`${endpoint}: Request initiated.`) let active = true; const id = setTimeout(() => { cons ...

Is there a way to use JQuery to make one button trigger distinct actions in two different divs?

For instance: Press a button - one div flies off the screen while another div flies in. Press the button again - Same div flies out, other div returns. I'm completely new to Javascript/JQuery so any assistance would be highly appreciated! Thank you ...

Obtain a segment of the string pathway

In this scenario, there is a file path provided below. Unlike the rest of the URL, the last part (referred to as video2.mp4) regularly changes. The language used for this project is either Javascript or Typescript. file:///data/user/0/com.sleep.app/files/ ...