【问题标题】:AngularJS - Simple $scope console.log() returns undefinedAngularJS - 简单的 $scope console.log() 返回未定义
【发布时间】:2014-09-14 02:20:37
【问题描述】:

我正在尝试从这个 $scope 中创建一个简单的console.log()

<div ng-controller="CustomerController" id="customer-block">

  <h3>Customer Information</h3>

  <div class="col-md-4">
      <label>Address 1:</label>
      <input type="text" ng-model="customer.address1" class="form-content"
        id="customer-address1" />
    </div>

    <div class="col-md-4">
      <label>Address 2:</label>
      <input type="text" ng-model="customer.address2" class="form-content"
        id="customer-address2" />
    </div>

    <div class="col-md-4">
      <label>City</label>
      <input type="text" ng-model="customer.city" class="form-content"
        id="customer-city" />
    </div>

</div>

这是我的 javascript 文件:

lima3app.controller("CustomerController", function($scope){

  console.log($scope.customer);

});

但是日志返回我undefined。这有什么问题?

这是plunkr:http://plnkr.co/edit/MU2i46o03bs22Jwh6QIe

【问题讨论】:

  • $scope.customer 没有在任何地方初始化,所以它应该是未定义的。在您在这些输入中键入内容后,它将开始有数据。

标签: angularjs logging console undefined


【解决方案1】:

正如其他人所说,您需要初始化客户对象。

由于控制器中没有客户集的值,因此它在视图中显示为未定义。当您在输入框中输入值时,这将不再是未定义的,但由于最初只进行一次日志记录,因此在输入框中输入值无效

Plunker Demo

这是我在 script.js 中更改的部分

lima3app.controller("CustomerController", function($scope){

$scope.customer = {
  address1 : 'address1',
  address2 : 'address2',
  city:'city'
}

console.log($scope.customer);

});

【讨论】:

    【解决方案2】:

    因为你的 JS 代码

    console.log($scope.customer);
    

    在初始化 CustomerController 控制器时运行,此时 $scope.customer 没有值,它返回 undefined。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 2014-04-18
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多