一尘不染

就地编辑内容编辑

angularjs

使用ng-repeat什么是能够编辑内容的最佳方法?

在我理想的情况下, 添加的 生日将是一个超链接,点击该链接将显示一个编辑表单-与带有更新按钮的当前添加表单相同。

实时预览(插播)

HTML:

<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script>
      document.write('<base href="' + document.location + '" />');
    </script>
    <script src="app.js"></script>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.0/css/bootstrap-combined.min.css"
    rel="stylesheet">
  </head>
<body ng-app="birthdayToDo" ng-controller="main">
    <div id="wrap">

      <!-- Begin page content -->
      <div class="container">
        <div class="page-header">
          <h1>Birthday Reminders</h1>
        </div>
            <ul ng-repeat="bday in bdays">
                <li>{{bday.name}} | {{bday.date}}</li>
            </ul>

           <form ng-show="visible" ng-submit="newBirthday()">
            <label>Name:</label>
            <input type="text" ng-model="bdayname" placeholder="Name" ng-required/>
            <label>Date:</label>
            <input type="date" ng-model="bdaydate" placeholder="Date" ng-required/>
            <br/>
            <button class="btn" type="submit">Save</button>
        </form>
      </div>

      <div id="push"></div>
    </div>

    <div id="footer">
      <div class="container">
        <a class="btn" ng-click="visible = true"><i class="icon-plus"></i>Add</a>
      </div>
    </div>
    </body>

App.js:

var app = angular.module('birthdayToDo', []);

app.controller('main', function($scope){

    // Start as not visible but when button is tapped it will show as true

        $scope.visible = false;

    // Create the array to hold the list of Birthdays

        $scope.bdays = [];

    // Create the function to push the data into the "bdays" array

    $scope.newBirthday = function(){

        $scope.bdays.push({name:$scope.bdayname, date:$scope.bdaydate});

        $scope.bdayname = '';
        $scope.bdaydate = '';

    };
});

阅读 208

收藏
2020-07-04

共1个答案

一尘不染

您应该将表单放在每个节点内,分别使用ng-showng-hide启用和禁用编辑。像这样:

<li>
  <span ng-hide="editing" ng-click="editing = true">{{bday.name}} | {{bday.date}}</span>
  <form ng-show="editing" ng-submit="editing = false">
    <label>Name:</label>
    <input type="text" ng-model="bday.name" placeholder="Name" ng-required/>
    <label>Date:</label>
    <input type="date" ng-model="bday.date" placeholder="Date" ng-required/>
    <br/>
    <button class="btn" type="submit">Save</button>
   </form>
 </li>

这里的关键点是:

  • 我已将控件更改ng-model为本地范围
  • 已添加ng-show到,form因此我们可以在编辑时显示它
  • 添加了span带有的,ng-hide以便在编辑时隐藏内容
  • 添加了ng-click,可以在其他任何元素中切换editingtrue
  • 更改ng-submit为切换editingfalse

这是您更新的Plunker

2020-07-04