【问题标题】:Cannot get value of ng-model through $scope无法通过 $scope 获取 ng-model 的值
【发布时间】:2017-09-06 15:13:26
【问题描述】:

我试图在单击一个按钮时获取 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,
    }
  }

谢谢!

【问题讨论】:

  • 奇怪,你能告诉我们你是如何包含控制器的吗?你在使用控制器吗?这是在指令中吗?
  • Works just fine。请记住,如果您提交时未在输入中添加任何内容,它将返回 undefined。
  • 代码运行正常,您的问题可能来自应用程序的其他部分...
  • @Keith 只是为了确保范围丢失是否存在任何问题,您可以尝试以下方法。将元素更改为 ng-model="parent.shipNameFirst" 然后在控制器中,添加以下行并尝试 $scope.parent = {}; console.log($scope.parent.shipNameFirst);
  • 您的代码应该可以工作。请在此处发布您的整个代码,以便我们检查出了什么问题以及为什么即使 $scope.stripeBtn 函数被触发,您的控制器也会失去其范围。

标签: javascript html angularjs angularjs-scope


【解决方案1】:

检查以下代码。它运行良好。

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>

【讨论】:

    猜你喜欢
    • 2016-06-12
    • 2015-12-05
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 2016-09-23
    • 1970-01-01
    相关资源
    最近更新 更多