当单击触发函数以将每个 ng-model 值添加到对象时,我试图获取 ng-model 的值。当尝试获取 $scope.shipNameFirst
的值时,它在第二个示例中显示为 undefined
。
我读到,最好在 View 上获取 $scope 的值,而不是通过 stripeBtn 函数传递它,所以理想情况下我想这样做。希望这是有道理的。
有人可以解释一下为什么这不起作用吗?
工作
HTML
<input type="text" ng-model="shipNameFirst">
<input type="text" ng-model="shipNameLast">
<button type="button" ng-click="stripeBtn(shipNameFirst, shipNameLast)">Checkout with Stripe</button>
Controller
$scope.stripeBtn = function(shipNameFirst, shipNameLast){
$scope.details = {
recNameFirst: shipNameFirst,
recNameLast: shipNameLast,
}
}
不工作
HTML
<input type="text" ng-model="shipNameFirst">
<input type="text" ng-model="shipNameLast">
<button type="button" ng-click="stripeBtn()">Checkout with Stripe</button>
Controller
$scope.stripeBtn = function(){
console.log($scope.shipNameFirst); //logging this (with $scope) comes up as undefined
$scope.details = {
recNameFirst: $scope.shipNameFirst,
recNameLast: $scope.shipNameLast,
}
}
谢谢!
最佳答案
检查以下代码。运行良好。
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope){
$scope.stripeBtn = function(){
console.log($scope.shipNameFirst);
$scope.details = {
recNameFirst: $scope.shipNameFirst,
recNameLast: $scope.shipNameLast,
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<input type="text" ng-model="shipNameFirst">
<input type="text" ng-model="shipNameLast">
<button type="button" ng-click="stripeBtn()">Checkout with Stripe</button>
</div>
关于javascript - 无法通过 $scope 获取 ng-model 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43342431/