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

Script did not deliver the expected outcome

I recently created a script using node.js and puppeteer to scrape the first title from multiple posts on a website. However, when I run the script, it doesn't return any results or generate any errors. Here is my script: const puppeteer = require(&a ...

Repair the navigation bar once it reaches the top of the screen using ReactJS

I have a webpage that contains specific content followed by a bar with tabs. My goal is to have this bar stay fixed at the top of the screen once it reaches that position while scrolling down, and only allow the content below the fixed bar to continue scro ...

Uploading with Javascript CORS consistently ends with an error event occurring

My current challenge is uploading a file to a server using JavaScript in compliance with the CORS specification. While there are numerous examples available online that successfully upload the file, I encounter an error as the final event being fired. Up ...

Determine the difference in time

There are two input types for time: 1. Time of entry. 2. Time of exit. For example: Start: 00:00 End: 01:30 Result: 1.5 Start: 14:00 End: 00:00 Result: 10 An algorithm needs to be created to calculate the number of employees working at a given time. Th ...

What sets local Node package installation apart from global installation?

My curiosity sparked when I began the process of installing nodemon through npm. Initially, I followed the recommended command and noticed the instant results displayed on the right side of my screen: npm i nodemon This differed from the installation ins ...

Tips for creating a universal function to connect html elements in AngularJS

As a beginner in angularJS, I come with prior experience writing common functions for binding html controls in JS. However, I am looking to apply the same approach in angularJS. I understand the angular way of binding html controls, but my goal is to str ...

Angular fails to refresh the display

For a while now, I have been working with Angular without encountering many difficulties. I have a controller that triggers a function on an ng-change event. This particular controller is responsible for generating different reports based on select filters ...

"Experiencing issues with the Ajax search functionality, need assistance

I am working on a JavaScript code to create search suggestions for a music search engine. The issue I am facing is that when the first character is typed, everything works fine. However, if I type more characters, all the results are displayed in a singl ...

Leveraging JavaScript's regular expressions to identify and capture the end of a

I am in need of using regular expressions (regex) to validate an ajax call to retrieve an output log from a server to check if a certain process is "finished". I have a PHP file that can provide the last line of the log under any circumstances. The Ajax ...

Creating a toggle label using just CSS: a step-by-step guide

Recently, I was trying to create a toggle label using HTML, CSS, and JavaScript. Here is the code snippet that I experimented with: function genre_itemclick(item){ if(item.classList.contains('light_blue_border_button')) { ...

Unleashing the power of specific dates with the angularJS datepicker directive

I am looking to develop a custom Datepicker directive using Angular JS, with the requirement of allowing only specific dates for selection by the user. For instance, I have a predefined list of numbers such as 1,3,5,7, and my goal is to make these particu ...

Using JSON in Highcharts: Customizing Border and Label Colors

Currently using Highcharts in JSON format with the following syntax: var neutral_color = '#c4c4c4', medium_grey = '#929292'; lineChartJSON['chart']['plotBorderColor'] = medium_grey; lineChartJSON['chart&ap ...

Ways to halt streaming without shutting down the Node.js server

I am currently facing an issue with closing a Twitter stream, as it causes my server to crash and requires a restart. Is there a way to close the stream without affecting the Nodejs (express) server? Here is the error message I am encountering: file:///mnt ...

Retrieve childNodes of the Select All input using jQuery from the container node with the class name "container"

I am trying to retrieve the text value of all the childNodes within the container of the corresponding input when the Select All checkbox is checked. Currently, my code captures the text inside each input label. However, it only logs the label (e.g. &apos ...

What is the best method for serving static files within a nested EJS view directory?

Assuming I have the directory structure below: |--Views/ | --partial/ | --links.ejs | |--assets/ | --css/ | --styles.css | |--server.js Code for links.ejs <link rel="stylesheet" type="text/css" href="css/forms/switches.css"& ...

How can we ensure that React state remains unaltered when modifying an array set to state?

Hope you're having a wonderful day! I'm encountering a significant problem with React. I have a state that contains an array. Within a function, I create a copy of the state in a new variable. However, any modifications made to this new variable ...

Using React hooks and Typescript: I was expecting to see an assignment or function call, but instead, an expression was

After working as a React developer for quite some time, my workplace recently introduced Typescript, which I am still getting familiar with. I implemented a custom hook for managing cookies, but the function it returns is generating an error. Here's ...

Utilizing Highcharts with NodeJS

Is anyone familiar with implementing Highcharts in Node.js? I am currently encountering a problem using [email protected]: var Highcharts = require('highcharts'), chart = Highcharts.chart(null, { series: [{ data: [1, 3, 2, 4 ...

Guide to running protractor to verify Google Chrome browser on Amazon Web Services

I have developed a SaaS platform using AngularJS / JBOSS, hosted on an AWS EC2 instance. We have thoroughly tested all our functionalities using unit and e2e tests, which work perfectly fine on local machines. However, we are facing issues with running the ...

How can VueJS cycle through the arrays within an object?

Is there a way to efficiently iterate through arrays within an object like in this example? I have a simple code snippet that currently outputs indexes in order, but I'm looking to access the values of the array instead. <template> <div&g ...