使用 angularjs 获取函数 return 的值

get function return value with angularjs

我正在尝试获取函数转换的结果并将其显示在页面上

这是我的函数:

$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;
        }
    }
}

调用函数的方式如下:

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

这里是我要显示结果的地方:

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

我很难显示结果...转换函数在我的控制器中:

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

而且按钮和我想放值的地方都在我控制器的范围内。帮助将不胜感激!

result分配给范围属性,例如

$scope.result = result;

并将其显示在您的模板中

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

趁我在这里,让我向您介绍一下 switch 声明

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;