未定义角度中某些变量的误差

Not defined error for some variables in angular?

本文关键字:变量 误差 未定义      更新时间:2023-09-26

我在codepen中使用以下代码并面临此问题,总之,我得到了以下错误

为什么它给出的错误是联系人而不是姓名?

我该如何解决这个问题?

angular.js:13550 ReferenceError: contact is not defined
    at new <anonymous> (pen.js:8)
    at Object.invoke (angular.js:4665)
    at R.instance (angular.js:10115)
    at n (angular.js:9033)
    at g (angular.js:8397)
    at g (angular.js:8400)
    at angular.js:8277
    at angular.js:1751
    at n.$eval (angular.js:17229)
    at n.$apply (angular.js:17329)

这是js文件

var app = angular.module("crud", []);
app.controller("ctrl", ['$scope', function($scope) {
    $scope.data = [3, 4, 5, 34, 34];
    debugger;
    $scope.name = name;
    $scope.contact = contact;
    $scope.obj = {
        name: $scope.name,
        contact: $scope.contact
    };
    console.log($scope.obj);
}]);

这是我正在使用的HTML文件。

<body ng-app="crud">
  <div ng-controller="ctrl">       
    <div>
      <table>
        <tr ng-repeat="x in data track by $index">
          <td>{{x}}</td>
          <td>{{$index}}</td>
        </tr> 
      </table>
    </div>
  </div>
</body>

请回答这些问题

  1. 为什么它在联系上失败而不是在名字上失败
  2. 联系人是数字数据,我应该给它什么默认值
  $scope.name = name;
  $scope.contact = contact;

它对联系人的抛出错误是因为你的应用程序中没有全局联系人变量,但如果你转到控制台并键入name。。有一个全局变量名等于CCD_ 1,所以它不会抛出错误。

如果您用任何其他变量替换$scope.name,它将为此引发错误。这一切都是因为名称是全局的,等于空字符串。

它为age而不是contact投掷的小提琴。http://fiddle.jshell.net/o6a54Lw5/1/

它为contact而不是name投掷的小提琴。http://fiddle.jshell.net/o6a54Lw5/2/

现在,如果您转到控制台并键入name,您将看到其声明的global

不要将全局变量的名称命名为name,因为它表示""0,因为

window.name获取/设置窗口的名称。

因此,它从未被定义,因此$scope将接受它

这是问题,

 $scope.contact = contact;

您没有在任何地方定义联系人和姓名。

Working APP