AngularJS - Simple $scope console.log() returns undefined

吃可爱长大的小学妹 提交于 2020-01-11 04:39:12

问题


I'm trying to make a simple console.log() from this $scope:

<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>

This is my javascript file:

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

  console.log($scope.customer);

});

But the log returns me undefined. What's wrong with that?

This is the plunkr: http://plnkr.co/edit/MU2i46o03bs22Jwh6QIe


回答1:


As the others have said, you need to initialize the customer object.

Since there is no value of customer set from controller, it is appearing as undefined in the view. When you enter values in the input boxes, this will no longer be undefined, but since logging is done only once initially, typing values in input box has no effect

Plunker Demo

Here is the part which I have changed in script.js

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

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

console.log($scope.customer);

});



回答2:


Because your JS code

console.log($scope.customer);

run when you init the CustomerController controller, at that time $scope.customer has no value and it return undefined.



来源:https://stackoverflow.com/questions/24901339/angularjs-simple-scope-console-log-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!