Unable to access the internal function of an Angular controller

My goal is to invoke the inner function of an Angular controller.

index.html

<script type="text/javascript>
        $(document).ready(function() {
            $('#example').multiselect({
                onChange: function(option, checked, select) {
                    //alert('Changed option ' + $(option).val() + '.');
                    var scope = angular.element(document.getElementById("MainWrap")).scope();

                    var n = $(option).val();

                    scope.$apply(function () {createMarker(data[n-1]);});             

                }
            });
        });
    </script>

controller.js

var mapApp = angular.module('mapApp', []);

mapApp.controller('mapContainer',function($scope){

    var mapOptions = {
        zoom: 10,
        center: new google.maps.LatLng(12,77),
        mapTypeId: google.maps.MapTypeId.TERRAIN
    }

    $scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);

    $scope.markers = [];
    var createMarker = function (info){

        var marker = new google.maps.Marker({
            map: $scope.map,
            position: new google.maps.LatLng(info.lat, info.long),
            name: info.name
        });
        $scope.markers.push(marker);

    };

});

I am able to console log data inside mapApp.controller, however, when I try to call the createMarker function, it shows an error: "createMarker is not defined." I followed this example for exposing the controller: http://jsfiddle.net/austinnoronha/nukRe/light/

Answer №1

For the function to work, it must be accessible through $scope.

$scope.addMarker = function (info){
    var newMarker = new google.maps.Marker({
        map: $scope.map,
        position: new google.maps.LatLng(info.latitude, info.longitude),
        name: info.title
    });
    $scope.allMarkers.push(newMarker);
};

In your template, make sure you access it using the controller's scope as well:

scope.$apply(function () {scope.addMarker(data[i]);}); 

This code assumes that the scope object being retrieved corresponds to the scope of mapView.

It should be noted that this is not an optimal AngularJS way of achieving this task. Ideally, a directive-based component should be utilized instead.

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

Is there a way to create a div that resembles a box similar to the one shown in the

Hello, I am attempting to achieve a specific effect on my webpage. When the page loads, I would like a popup to appear at the center of the screen. To accomplish this, I have created a div element and initially set its display property to 'none'. ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

Steps for sending a form with jQuery's submit method1. Start

Below is the jquery code that I have written: $(document).ready(function () { $('.bar_dropdown').on('change', function() { console.log("dropdown changed") $('#bar_graph_form_id').submit(function(e ...

The timer freezes briefly at 1:60 before switching to 1:01

I'm in the process of creating a website for Rubik's cube scrambling and timing, and everything seems to be working well so far. I have implemented a scrambler, a timer, and a list of recorded times (still a work in progress). The timer is functi ...

Determine ng-checked according to an array

I am working with a select dropdown that creates checkboxes using ng-repeat based on the selected value. The goal is to have all values in the dropdown selected, corresponding checkboxes checked, and store them in an array. Each time a checkbox is changed ...

Rendering Error - Animating text using React and Material-UI

Looking for a way to create a scrolling effect line by line? I have a component with name, pronouns, and some humble sub-text that should scroll one item at a time. To handle the scrolling feature, I've set up a separate component called TitleScroll. ...

Does JSX have an API that can handle self-closing tags, such as <br>, if they are not closed properly?

For my latest project, I've been working on a ReactJS component using JSX and it looks something like this: <script type="text/jsx"> var HelloWorld = React.createClass({ render: function() { return ( < ...

The operation malfunctions if the variable input is below 50, causing it to produce inaccurate results

The function "calcFinalTotal()" was created to calculate the post-tax discount on a purchase of items that were previously totaled and stored in an input tag with the ID of "totaltaxamount". This function applies a 10% discount to orders between $50 to $ ...

Setting up Access-Control-Allow-Origin in WildFly 8.1.0 configuration

I am attempting to configure Access-Control-Allow-Origin on a Wildfly 8.1.0 server using the standalone.xml file provided below: <?xml version='1.0' encoding='UTF-8'?> <server xmlns="urn:jboss:domain:2.1"> <extensio ...

Searching patterns in Javascript code using regular expressions

I am dealing with two strings that contain image URLs: http://dfdkdlkdkldkldkldl.jpg (it is image src which starts with http and ends with an image) http://fflffllkfl Now I want to replace the "http://" with some text only on those URLs that are images. ...

Develop a feature within an Angular directive to implement a button that can delete the directive completely

If I have an element called "filterList" containing angular directives in the form of <filter-item>, and I want each <filter-item> to include a delete button that removes it from the DOM when clicked, how can I achieve this? <div class="fil ...

Troublesome update: Migrating XState's Reddit example from Vue 2 to Vue 3

Recently, I delved into the XState documentation and decided to explore the Reddit sample provided in the official guide. You can find it here: As I attempted to upgrade the sample implementation to Vue 3 following the work of Chris Hannaby, I encountered ...

Error occurred within node while attempting to create a directory using mkdirsync

I wrote some code. try{ var Storage = multer.diskStorage({ destination: function (req, file, callback) { fs.mkdirSync('/home/data/' + file.originalname, { recursive: true }, (error) => { ...

Struggling to get Angular Formly to properly inject into my module

Hello there! I am having trouble injecting formly and formlyBootstrap into my module. angular.module('myApp', ['formly', 'formlyBootstrap', function config(formlyConfig) { formlyConfig.setType([ { ...

Real-time page updates and on-the-fly event monitoring

As I tackle a specific logical challenge, I find myself struggling a bit. Here is the issue at hand: When sending a PUT request from within a controller using certain factory methods, my aim is to update the data without triggering a page refresh. For exa ...

Issues with AngularJS data binding functionality

For some reason, I'm facing an issue where the data retrieved from my backend is not displaying in the component. Even though logging response.data shows the correct data, it doesn't bind when assigned to the movies variable within the scope. Her ...

Extension for Chrome - view source of current webpage

I'm attempting to develop my chrome extension to extract the current page source and identify the current URL, as seen in this example. If I were to visit https://www.google.com and the page source contains google I want my extension to display a ...

Issue with ng-change in dropdown selection

It seems like this function isn't working properly and I can't figure out why. This is my view: <tr> <th>Category</th> <td> <select class="form-control" ng-model="masterlist.category_id" ng-options="c.c ...

Interacting with an XML file contained within a PHP variable using jQuery

I'm pretty new to programming, so please be patient with me =] Currently, I am working on passing a string from the user to an API using PHP. The API then responds with an XML file, which I store under $response. So far, everything is running smoothl ...

Utilizing jQuery to gather the values of all checkboxes within each group and dynamically adding them to a span element for counting purposes

I am currently working on a project that involves sets of groups with checkboxes. My goal is to retrieve the value of each checkbox when checked and add this value to a counter span element located beside it. However, I have encountered an issue where clic ...