ashwinm
ashwinm

Reputation: 636

Can't call inner function of angular controller

I want to call 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 but when calling createMarker function shows Error: createMarker is not defined error. Followed this example to expose controller http://jsfiddle.net/austinnoronha/nukRe/light/

Upvotes: 0

Views: 166

Answers (1)

David L
David L

Reputation: 33863

The function will only be callable if exposed on $scope.

$scope.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);
};

In your template, you will also need to access it via controller scope:

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

This assumes that the scope object you are retrieving correlates to the scope of mapContainer.

It's worth noting that this is a pretty anti-angulary way to do something. The correct approach would be to create a directive-driven component.

Upvotes: 1

Related Questions