我的文本没有添加到Angular js中的列表项中

My text not add in list item in Angular js?

本文关键字:js 列表 Angular 文本 添加 我的      更新时间:2023-09-26

HI我正在创建一个新表单并填写一些文本并提交,但我的文本没有保存

你能帮我吗

如果我单击一个按钮添加新的而不是显示表单,请在表单中添加详细信息并保存但不保存。

我是ANgular的新手

我的代码是这个

ANgular Js

var app = angular.module('myApp', []);
app.controller('myController', function($scope){
  $scope.peopleName = '';
  $scope.peopleSex = '';
  $scope.peple=[
    {name:"Saml", sex:"M"},
    {name:"somi", sex:"M"},
    {name:"jokyineya", sex:"F"}
    ];

    $scope.newItem = function(name, sex){
      if (this.peopleName === '') return;
       $scope.peple.push({
            name: title,
            sex: label
        });
        this.peopleName= "";
        this.peopleSex= "";
        this.showForm = false;
    }
})

HTML代码是

<body ng-app="myApp">
  <div class="" ng-controller="myController">
    <form ng-submit="newItem(peopleName, peopleSex)" ng-show="showForm">
      Name
      <input type="text" ng-model="peopleName" />
      <br />
      <br />Sex
      <input type="text" ng-model="peopleSex" />
      <br />
      <br />
      <input type="button" value="Submit" />
      <br />
      <br />
      <br />
      <br />
    </form>
    <button ng-click="showForm=true; ">Add new</button>
    <ul>

      <li></li>
      <li ng-repeat="person in peple">
        {{person.name}} {{person.sex}}
      </li>
    </ul>
  </div>
</body>

演示

只需要做一些更改

工作演示

标题更改为名称并将label改为sex,如下所示

$scope.peple.push({
name: title,
sex: label
});

按钮更改为提交

<input type="submit" value="Submit" />

您的问题是"title"answers"label":

$scope.newItem = function(name, sex){
  if (this.peopleName === '') return;
   $scope.peple.push({
        name: title, // this should be name
        sex: label // this should be sex
    });
    this.peopleName= "";
    this.peopleSex= "";
    this.showForm = false;
}

看起来应该是这样的:

$scope.newItem = function(name, sex){
  if (this.peopleName === '') return;
   $scope.peple.push({
        name: name,
        sex: sex
    });
    this.peopleName= "";
    this.peopleSex= "";
    this.showForm = false;
}

您误解了这里的一些内容。但它很容易修复。当您在html中使用ng模型时,您已经将它们写入$scope,因此不需要将它们作为参数发送。

$scope.newItem = function(){
  if ($scope.peopleName === '') return;
   $scope.peple.push({
        name: $scope.peopleName,
        sex: $scope.peopleSex
    });
    $scope.peopleName= "";
    $scope.peopleSex= "";
    $scope.showForm=false;
}

并称之为

<form ng-submit="newItem()" ng-show="showForm">

您还需要按之前的回答提交按钮。

html更改为:
<form ng-submit="newItem()" ng-show="showForm">
newItem的作用是:

$scope.newItem = function(name, sex){
  if (this.peopleName === '') return;
   $scope.peple.push({
      name: $scope.peopleName,
      sex: $scope.peopleSex
  });
  $scope.peopleName= "";
  $scope.peopleSex= "";
  $scope.showForm = false;
}

Angularjs使用$scope将值绑定到html,所以我建议尽可能使用它。