以角度添加到列表功能

Add to list functionality in angular

本文关键字:列表 功能 添加      更新时间:2023-09-26

我是 angular 的新手,并试图实现添加到列表功能。我有几个问题

  1. 为什么$scope.newChatconsole.log返回未定义
  2. 由于吊装可变,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的控制台.log返回未定义

您在作用域上获得 NewChat console.log($scope.newchat);尝试使用控制台日志记录console.log(newchat);它们都与 ng-model 中的 Newchat 相同,使其在作用域中可用。在下面的演示中单击发送按钮后查看控制台

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

否,由于ng模型数据绑定,它可用

演示

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>

控制器更改为以下内容

.controller('ChatsCtrl', function($scope, Chats) {
  $scope.newchat = {};
  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  }
  $scope.sendChat = function(newchat){
    Chats.set(newchat);
    console.log($scope.newchat); //now you will have your $scope.newchat
    newchat.lastText  = "";
  }
})