无法通过$ scope获得ng-model的值

时间:2017-04-11 09:48:30

标签: javascript html angularjs angularjs-scope

当我点击一个触发函数的按钮时,我试图获取ng-model的值,以便将每个ng-model值添加到一个对象。在尝试获取$scope.shipNameFirst的值时,在第二个示例中它会显示为undefined

我已经读过,最好在视图上获取$ 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>

控制器

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

控制器

  $scope.stripeBtn = function(){

  console.log($scope.shipNameFirst); //logging this (with $scope) comes up as undefined

    $scope.details = {
      recNameFirst: $scope.shipNameFirst,
      recNameLast: $scope.shipNameLast,
    }
  }

谢谢!

1 个答案:

答案 0 :(得分:0)

检查以下代码。它工作得很好。

&#13;
&#13;
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,
    }
  }
});
&#13;
<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>
&#13;
&#13;
&#13;