2016-08-03 63 views
7

我使用下面的代码在codepen和面对这个问题, 为conctact我收到以下错误角度中的一些变量没有定义错误?

为什么给错误的接触,而不是为了名?

我该如何解决这个问题?

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. 联系人是号码数据,我应该给它什么默认值?
+1

你在你所分配给'$ scope.contact'接触得到什么? –

回答

4
$scope.name = name; 
    $scope.contact = contact; 

其用于接触投掷的错误是因为在您的应用程序没有全球性的接触变量,但如果你去到控制台,输入名称..有相当于""这样一个全局变量名它不会抛出错误。

如果用任何其他变量代替$scope.name,它会为此引发错误。它的全部是因为名字是全球性的,等于空串。

一个小提琴,它抛出age而不是contacthttp://fiddle.jshell.net/o6a54Lw5/1/

一个小提琴,它抛出contact而不是namehttp://fiddle.jshell.net/o6a54Lw5/2/

现在如果你去到控制台,输入name第二小提琴,你会看到它的声明global

+0

谢谢。和这一个 - 联系人是数字数据,我应该给它的默认值是什么? –

+0

您可以根据您的应用需求提供任何东西,$ scope.contact = 0;或者你想保留它的任何价值...... – Thalaivar

0

这里是问题,

$scope.contact = contact; 

你还没有在任何地方定义的联系人和名称。

Working APP

+0

我还没有定义名称。 –

+0

请再次阅读这个问题,并尝试回答确切的问题。 –

+0

@AnkurMarwaha查看示例应用程序 – Sajeetharan

2

,因为它代表window.name因为,

window.name获取/设置窗口的名称,不要为一个全局变量给予名称name

出于这个原因,它从来没有不确定的,所以$scope将接受它