gpt4 book ai didi

javascript - 如何在 AngularJs 中重用 HTML/ Controller 来添加/编辑用户

转载 作者:行者123 更新时间:2023-12-03 10:01:56 26 4
gpt4 key购买 nike

我有两个单独的 HTML 模板用于添加/编辑用户,因此有两个单独的 Controller 。 我如何拥有一个 HTML 文件和一个 Controller 来实现添加/编辑功能。

添加用户

  <div>
<label>FirstName</label>
<div>
<input type="text" name="name" data-ng-model="register.Student.FirstName">
</div>
</div>
<div>
<label>LastName</label>
<div>
<input type="text" name="name" data-ng-model="register.Student.LastName">
</div>
</div>

编辑用户

  <div>
<label>FirstName</label>
<div>
<input type="text" name="name" data-ng-model="student.Student.FirstName">
</div>
</div>
<div>
<label>LastName</label>
<div>
<input type="text" name="name" data-ng-model="student.Student.LastName">
</div>
</div>

AddController 将 FirstName 和 Last Name 初始化为 null 值。我的 EditController 中并非如此。

       $scope.register = {
User: {
FirstName: '',
LastName: '',
};

我的路线配置

 templateUrl: '/app/users/newStudent.html',
controller: 'newStudentController',
controllerUrl: '/app/users/newStudentController.js',

templateUrl: '/app/users/editStudent.html',
controller: 'editStudentController',
controllerUrl: '/app/users/editStudentController.js',

最佳答案

合并两个 html 文件并将其命名为 student.html 并合并两个 controller 文件并将其命名为 student .js.

student.js

app.module('myApp', []).controller('studentController', function () {})

您的路线配置:

templateUrl: '/app/users/student.html',
controller: 'studentController',
controllerUrl: '/app/users/student.js',

更新

演示:http://jsfiddle.net/softvar/uh17tseh/1/

HTML:

<div ng-app="myApp" ng-controller="myController">
<div ng-repeat="stud in students">
<div ng-hide="isEditForm">
<span>{{stud.name}} - {{stud.age}}</span>
<button ng-click="isEditForm=true;">Edit Student</button>
</div>
<div ng-show="isEditForm">
<label>Enter Name</label><input ng-model="stud.name" />
<label>Enter Age</label><input ng-model="stud.age" />
<button ng-click="isEditForm=false;">Save</button>
</div>
</div>
<br/><br/>

<div ng-hide="isAddForm">
<button ng-click="isAddForm=true;">Add Student</button>
</div>
<div ng-show="isAddForm">
<label>Enter name</label><input ng-model="newStudent.name" />
<label>Enter Age</label><input ng-model="newStudent.age" />
<button ng-click="addStudent()">Add</button>
<button ng-click="isAddForm=false;">Cancel</button>
</div>
</div>

JS:

var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.students = [
{"name": "ABC", "age": 21},
{"name": "DEF", "age": 22},
{"name": "GHI", "age": 23},
{"name": "XYZ", "age": 24}
];
$scope.newStudent = {};
$scope.addStudent = function () {
if ($scope.newStudent.name && $scope.newStudent.age) {
$scope.students.push({"name": $scope.newStudent.name,"age": $scope.newStudent.age});
$scope.isAddForm = false;
}
};
});

关于javascript - 如何在 AngularJs 中重用 HTML/ Controller 来添加/编辑用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com