Invoking a function by passing arguments within $Scope does not work

Asked

Viewed 89 times

0

I have a function in a file called "mapHelper.js" responsible for adding popups on a map:

     function writeMarker(x,y,msg) {
     var muxiCoordinates = [x,y];
     var muxiMarkerMessage = msg;
     L.marker(muxiCoordinates).addTo(map).bindPopup(muxiMarkerMessage).openPopup();
     }

A controller that allows you to read the database data to $Scope.markers. The data is a list of coordinates and messages "x,y,msg"

angular.module("app",[]);
angular.module("app").controller("appCtrl",function($scope,$http){
    $http.get('/markers').then(function (res) {
        console.log("Got the data");
        $scope.markers=res.data;
    });
});

The question is: how to invoke this function by passing the arguments within $Scope?

I thought of something like:

    div(ng-repeat="marker in markers")
        script.
            writeMarker({{marker.x}},{{marker.y}},{{marker.msg}});

but it doesn’t work.

  • I’m not sure what your application looks like, but inside $http.get('/markers').then(function (res) { you could do directly res.data.forEach(marker => writeMarker(marker.x, marker.y, marker.msg));. You can test that?

1 answer

1


If your intention is to display exactly when the angular $http return happens, you can pass in the same Response.

angular.module("app",[]);
angular.module("app").controller("appCtrl",function($scope,$http){
    $http.get('/markers').then(function (res) {
        console.log("Got the data");
        for(var i = 0; i < resp.data.length; i++){
            var data = resp.data[i];
            writeMarker(data.x,data.y,data.msg);
        }
    });
});

Now, if you want to use this javascript function dynamically, you can pass the javascript function to a scope angle, and then use with a ng-click or something like, as you intended to do:

$scope.writeMarker = writeMarker;
  • 1

    Very good, thank you. Problem solved

  • If the answer solved your problem, could you select it as right to help future users? Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.