为什么回调函数在$ scope中不起作用? Angularjs

时间:2014-02-20 11:26:14

标签: angularjs

为什么函数getPrice('Table')在控制器中不起作用?它返回undefined而不是400.这非常适用于普通的JS(没有$scope)。

function MyCtrl($scope) {   

$scope.prices = [{
    name: 'Bed',
    price: 900
}, {
    name: 'Table',
    price: 400
}];


$scope.getPrice = function (name) {
    $scope.prices.forEach(
    function (el) {
        if (el.name == name) {
            return el.price;
        } else {
            return null;
        }
    }
    );
}
};

1 个答案:

答案 0 :(得分:1)

您的getPrice函数不会返回任何内容。试试这个:

 $scope.getPrice = function (name) {
             $price = null;
             $scope.prices.forEach(
                     function (el) {
                         if (el.name == name) {
                             $price =  el.price;
                             return;
                         } else {
                             return;
                         }
                     }
             );
             return $price;
         }