我是Angel的新手,正在尝试实现添加到列表功能。我有几个问题


为什么console.log$scope.newChat返回未定义
由于变量提升,newChat是否可用于sendChat()调用。


模板

<ion-list>
      <ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap" href="#/tab/chats/{{chat.id}}">
        <img ng-src="{{chat.face}}" >
        <h2>{{chat.name}}</h2>
        <p>{{chat.lastText}}</p>
        <i class="icon ion-chevron-right icon-accessory"></i>

        <ion-option-button class="button-assertive" ng-click="remove(chat)">
          Delete
        </ion-option-button>
      </ion-item>
      <ion-item >
        <form ng-submit="sendChat(newchat)"> <!-- this line in question 2 -->
            <label class="item item-input">
              <input type="text" placeholder="What do you need to do?" ng-model="newchat.lastText">
            <button type="submit" class="button button-right button-positive">Send</button>
            </label>
          </div>
        </form>
      </ion-item>
    </ion-list>


控制者

.controller('ChatsCtrl', function($scope, Chats) {
  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  }
  $scope.sendChat = function(newchat){
    Chats.set(newchat);
    console.log($scope.newchat); //this line in question 1
    newchat.lastText  = "";
  }
})

最佳答案

1)为什么$ scope.newChat的console.log返回未定义


您在作用域console.log($scope.newchat);上遇到了新聊,请尝试使用console.log(newchat);进行控制台日志记录,因为它们都与ng-model中的newchat相同,所以在作用域上可用。单击下面演示中的“发送”按钮后,查看控制台


  2)由于变量提升,newChat是否可用于sendChat()调用。


否,由于ng-model数据绑定而无法使用

演示版



angular.module('myApp',[])
.controller('ChatsCtrl', function($scope) {
  //$scope.chats = Chats.all();
  $scope.remove = function(chat) {
    //Chats.remove(chat);
  }
  $scope.sendChat = function(newchat){
   // Chats.set(newchat);
    console.log($scope.newchat); //this line in question 1
    newchat.lastText  = "";
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ChatsCtrl"> <form ng-submit="sendChat(newchat)"> <!-- this line in question 2 -->
            <label class="item item-input">
              <input type="text" placeholder="What do you need to do?" ng-model="newchat.lastText">
            <button type="submit" class="button button-right button-positive">Send</button>
            </label>

        </form>

 </div>

08-08 05:01