Unable to modify the variable within angular.js

I have been working on developing an Ionic application with angular.js and I am almost done, but I have encountered a minor issue.

Inside my templates/menu.html file, I have the following code:

<ion-item nav-clear menu-close ng-click="filterByPeriod(weekBegin, currentDate)">Filter  </ion-item>

and in my controller.js file:

.controller('Home', ['$scope', '$ionicModal', '$cordovaGeolocation', function($scope, $ionicModal, $cordovaGeolocation) {
  App = {
    init: function() {
      setTimeout(function(){
        $scope.map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
      }, 200);
    },
  };
  $scope.addMarkersToMap = function(reports, map) {
    var newCenter = new google.maps.LatLng(reports[0].latitude, reports[0].longitude);

    map.setCenter(newCenter);
    map.setZoom(12);
  }

  $scope.filterByPeriod = function(beginDate, endDate) {
    var cityId = window.localStorage.getItem('cityId');

    serviceReports.getDenunciasFromPeriod(cityId, beginDate, endDate)
    .success(function(reports){
      $scope.addMarkersToMap(reports.dados, $scope.map);
    });
  }
  App.init();
}]);

I have tried using `$scope.apply(function(){}) to encapsulate the method, but I am still getting the following error:

Does anyone have any suggestions on how to resolve this issue?

Answer №1

It appears that $scope.map is undefined. This could be due to not receiving data from the Google Maps library or the data not being fully loaded yet. Consider implementing a promise to handle the variable or disabling the button until the data is available.

Answer №2

It seems like there is an issue with how your map object is being initialized. The document.getElementById("map-canvas") function may not be working correctly in a controller, as DOM manipulation is not synchronized with the angular digest cycle.

Consider using a directive instead. You can see an example of how to do this in the following link:

https://github.com/bennekrouf/ng-formation/blob/master/app-directives/app/app.js

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

employing document.write() specifically for a designated division

This is the coding: $(document).ready(function(){ var Jstr = { "JSON" : [ { "Eid" : 102,"Ename":"", "Ecode" : "<input type ='text'/>", "Eprops": {"name": "", "value":"", "maxlength":""}} ] } ; $(".search").click(funct ...

Firestore Query sends data object to browser

When making a Firestore query, the browser is displaying [object Object],[object Object] instead of the expected output: router.get('/jobopportunities', async(req, res) => { var jobArray = []; const snapshot = await fireba ...

What is the most efficient method to import multiple MaterialUI components using a shared namespace without requiring the entire library to be imported

In order to prevent name mixing with other libraries, I want my MaterialUI components to be under the same namespace. For example, ensuring that <Box> references <MaterialUI.Box> and not <SomeOtherLibrary.Box>. Although it seems like a si ...

"Material-UI enhanced React date picker for a modern and user-friendly

Currently, I am utilizing the Date picker feature from Material UI. The code snippet responsible for implementing it is as follows: import { DatePicker } from 'redux-form-material-ui'; <Field name="birthDate" ...

Looking for a Plugin that Can Responsively Display Images in a Vertical Layout - Does One Exist using Jquery

Looking for a gallery slider plugin that is responsive both horizontally and vertically. Have tried Flexslider1/2, Galleria, and others but they do not adjust to vertical resizing. Changing the CSS did not help. If you resize the browser horizontally with ...

Functionality of retrieving arrays from PHP via jQuery ajax (JSON) runs smoothly, however encounters issues specifically on web server

No solutions have been able to solve the problem at hand despite finding similar questions. function loadProject(id) { $.ajax({ url: 'loadDrumsetData.php', type: 'GET', data: { i: id }, ...

Real-time data and dynamic checkbox functionality in AngularJS

I am working on an onclick function that involves data stored in objects. $scope.messages = [ {"id": "1"}, {"id": "2"}, {"id": "3"}, {"id": "4"}, ]; $scope.selection = { ids: {} }; $scope.sendMe = function(message) { //send the data with `id` and ...

How to stop the previous page from reloading with Express.js routing?

Just starting out with express and web development in general, I have a question regarding routing. Currently, I am working on a web app using Firebase with pure JS and implementing routing on Firebase cloud functions. The routing logic is outlined below: ...

Attempting to store an array of JSON objects in the state, and then utilizing the `map` method to render

I'm just starting out with React. Currently, I'm attempting to store an array of JSON objects in the state and then map those items into the component render. I'm feeling a bit lost on how to debug this as there are no console errors showi ...

As two divs glide across the screen, the top div remains hidden from view

To enhance our user experience, we are tasked with creating a captivating screen saver featuring 3 images. The bottom image will remain fixed in its position. The middle image should move across the screen. Lastly, the top image will move at a faster ...

Struggling with implementing jQuery AJAX in Node.js Express - any tips?

Struggling with implementing ajax in node js for the first time. I've been testing it using the console, but unable to get a response. Here's my code: <script> function getMessage() { var data = $("#messageselect").val() $.ajax({ ...

The div element fails to display even after invoking a JavaScript function to make it visible

As a newcomer to JavaScript & jQuery, please bear with me as I ask a very basic question: I have created the following div that I want to display when a specific JavaScript function is called: <div id='faix' class="bg4 w460 h430 tac poa ...

The sinuous waveform in JavaScript

track : function(x, y, top, ampl) { return { top : top + 2, x : x + ampl * Math.sin(top / 20), y : (top / this.screenHeight < 0.65) ? y + 2 : 1 + y + ampl * Math.cos(top / 25) }; } This specif ...

Utilizing jQuery or JavaScript to transfer information within a Bootstrap modal

I am working with a table that is generated from an SQL Table using PHP for data looping. HTML <tbody> <?php $no = 1; foreach($data_request as $data) { ?> <tr> <td class="center"><?php echo $no++.". ";?> ...

Node.js and Express: ensuring completion of asynchronous operation before responding to HTTP request

Imagine there is a callback function set up for an HTTP GET request, structured like this: router.get('/latestpost', function(req, res, next) { var data = new FbData(); get_latest_post (data); get_post_image (data); res.json(da ...

Explore various date formats using the datepicker functionality

I'm dealing with the code below: <script type="text/javascript" language="javascript" src="~/Scripts/bootstrap-datepicker.min.js"></script> <script type="text/javascript" language="javascript" src="~/Scripts/locales/bootst ...

Are there any risks associated with using nested setTimeout functions with the same name?

While reviewing the source code of typed.js, I noticed that the main function in this plugin utilizes a design pattern with multiple setTimeout functions nested inside one another. Here is a snippet of the code: self.timeout = setTimeout(function() { / ...

How can I add multiple filters to a Kendo Grid?

Is there a way to include two separate filter fields for date filtering in Kendo Grid UI? Currently, the method I am using only allows for one date filter to be displayed. filterable: { ui: function (element: any) { element.ken ...

Is there a way to append items to the main level of an array?

I am attempting to populate an array with objects in order to achieve the following structure: myobject1: Object: ItemInside: Object myobject2: Object ItemInside: Object myobject3: Object ItemInside: Object myobject4: Object ItemInside: Ob ...

Two distinct controllers: concealing elements through the operation of one of them

I am facing a challenge with my HTML elements: In one form-group, I have the following input: <div class="form-group"> <input type="search" ng-model="search"/> </div> This particular form-group needs to be hidden when another form-g ...