简体   繁体   中英

get function return value with angularjs

I am trying to get the result of my function convert and display it on the page

Here is my function:

$scope.convert = function(myUnit, myUnit2, distance){
    var result = 0;
    if(myUnit === "Kilometer"){
        if(myUnit2 === "Kilometer"){
            result = distance;
        }
        else if(myUnit2 === "Meter"){
            result = distance * 1000;
        }
        else if(myUnit2 === "Centimeter"){
            result = distance * 100000;
        }
        else if(myUnit2 === "Millimeter"){
            result = distance * 1000000;
        }
        else if(myUnit2 === "Mile"){
            result  = distance * 0.621371;
        }
        else if(myUnit2 === "Nautical Mile"){
            result = distance * 0.539957;
        }
    }
}

Here is how the function is called:

<button class="button button-block button-balanced" ng-click="convert(myUnit.thisunit, myUnit2.thisunit2, formData.distance)">
     Convert
</button>

Here is where I want to display the result:

<label class="item item-input" style="border-style: solid;
                border-color: black;">
     <span class="input-label">Result:</span>
     <p>DISPLAY RESULT HERE</p>
</label>

I am having a hard time displaying the result... The convert function is inside my controller:

myApp.controller('mainController', ['$scope', function($scope)

And the button and the place I want to put the value are within scope of my controller. Help would be appreciated!

Assign result to a scope property, eg

$scope.result = result;

and display it in your template

<p>{{ result }}</p>

While I'm here, let me introduce you to the switch statement

var result = 0;
if(myUnit === "Kilometer"){
    switch (myUnit2) {
        case 'Kilometer' :
            result = distance;
            break;
        case 'Meter' :
            result = distance * 1000;
            break;
        // you get the idea
    }
}
$scope.result = result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM