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

标签 javascript html angularjs angularjs-scope

当单击触发函数以将每个 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/

相关文章:

javascript - Bootstrap 切换 : One on the rest off

javascript - 在 React Native 中调用自定义组件的 onPress

javascript - 使用 addEventListener onSubmit 表单

javascript - 在 mousedown 和 mousemove 事件中获取鼠标位置

html - CSS 防止盒子阴影颜色渗色

javascript - 环境设置 egghead.io 教程?

javascript - 相当于用数字键拼接一个对象

javascript - 循环遍历 HTML 元素不适用于返回的 prevObject

javascript - ES6箭头(=>)功能与IE不兼容?

javascript - AngularJS - 如何在多个实例中限制 ngClick 的范围