函数参数在angularjs中未定义

时间:2016-10-15 06:29:16

标签: angularjs

为什么功能 CarName 参数传递为未定义,为什么实际值不能检索?

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
    $scope.carname = "Honda";

    $scope.SaveData = function (carname) {

        console.log('Car Name='+carname);

    };
})

3 个答案:

答案 0 :(得分:1)

如果您没有在某些事件上将数据绑定到ui,则无需在此处使用函数,

您可以使用$scope.carname

 console.log('Car Name='+$scope.carname);

答案 1 :(得分:0)

试试这个有用的演示

<div ng-app="myApp" ng-controller="myCtrl">
    <button ng-click="SaveData(carname )">Save</button>
</div>

var app = angular.module('myApp', []);

app.controller('myCtrl', function ($scope) {
    $scope.carname = "Honda";
    $scope.SaveData = function (carname) {
        alert(carname)
        console.log('Car Name='+carname);
    };
 })

点击http://codepen.io/vkvicky-vasudev/pen/XjkZBN

如果您尝试使用对象

var obj = [{ name: "Honda", Year: 2016 }]; // then simply do like this

$scope.SaveData = function () {
    alert(carname)
    console.log('Car Name=' + obj);
};

或者如果你想要范围变量那么

$scope.obj = [{ name: "Honda", Year: 2016 }]; // then simply do like this

$scope.SaveData = function () {
    alert(carname)
    console.log('Car Name=' + $scope.obj);
};

答案 2 :(得分:0)

是,不需要参数。

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
    $scope.carname = "Honda";

    $scope.SaveData = function () {

        console.log('Car Name='+carname);

    };
})