Search code examples
angularjsmodel-view-controllerionic-frameworkangularjs-scope

Use returned array from $scope function in the controller


In my controller I have created $scope function which returns an array. That function uses data from view with ng-model directive and everything is working fine (when I call this function with the expression in the view I get returned data), except when I want to use that returned array in my controller, I simply get nothing.

Plunker

JS code:

app.controller('CalculatorCtrl', function($scope) {

  $scope.deparature = {
    'lat_1': '',
    'lat_2': '',
    'lat_3': '',
    'long_1': '',
    'long_2': '',
    'long_3': ''
  }

  $scope.arrival = {
    'lat_1': '',
    'lat_2': '',
    'lat_3': '',
    'long_1': '',
    'long_2': '',
    'long_3': ''
  }

  $scope.select = {
    'departure_1': '',
    'departure_2': '',
    'arrival_1': '',
    'arrival_2': ''
  }

  $scope.depCoordinate = function() {

    var cordLat = $scope.deparature.lat_1 + '/' + $scope.deparature.lat_2 + '/' + $scope.deparature.lat_3 + '/';

    if ($scope.select.departure_1 === 'S') {
      var temp = '-' + cordLat;
      var CordLatS = Dms.parseDMS(temp);
    } else {
      var CordLatS = Dms.parseDMS(cordLat);
    };

    var cordLong = $scope.deparature.long_1 + '/' + $scope.deparature.long_2 + '/' + $scope.deparature.long_3 + '/';

    if ($scope.select.departure_2 === 'W') {
      var temp = '-' + cordLong;
      var CordLongW = Dms.parseDMS(temp);
    } else {
      var CordLongW = Dms.parseDMS(cordLong);
    };

    return [CordLatS.toFixed(5), CordLongW.toFixed(5)];
  }

  var cord = $scope.depCoordinate();
  var lati = cord[0];
  console.log(lati);

  /*I need to pass the array result to var p1. How I can do that?*/
  $scope.distance = function () {
      var p1 = new LatLon(50.06632, -5.71475);
      var p2 = new LatLon(58.64402, -3.07009);
      return p1.distanceTo(p2);

};
});

Solution

  • First, there are some things in your plunker that should be relevant here:

    1. NEVER do this: <p>Test: {{ depCoordinate() }}</p>.

    It will call your function several times causing several problems.

    1. Don't use ng-init() for this kind of thing: <div class="list" ng-init="initWaves()">. It should be used only in specific cases (i.e. ng-repeat), check the docs.

    Then.. If I understood your question well, you want to use the returned array in your view, so, if I'm correct, here is how-to:

    $scope.array = [CordLatS.toFixed(5), CordLongW.toFixed(5)];
    return $scope.array;
    

    And in your view just use it:

    {{ array }} // or whatever you want to do with it.