ng-model 没有在 AngularJS 中更新正确的用户



我是AngularJS中的新手,我有一个用户可以在那里编辑表单的表单。但是当用户单击"更新"时,它会更新表单。但是,用户不会更新用户。如图所示 图片在这里

这是我的代码:

<div ng-controller="MyCtrl">
<div class="people-view">
<h2 class="name">{{people.first}}</h2>
<h2 class="name">{{people.last}}</h2>
<span class="title">{{people.title}}</span>
<span class="date">{{people.date}} </span>
</div>
</div>
</div>
<!-- the form -->
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="myObject.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="myObject.last">
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="update()">Update</button>


</form> 

应用.js

var app = angular.module("Portal", ['ngRoute']);

app.controller('MyCtrl',  function($scope) {
$scope.inactive = true;
$scope.people = {};
$scope.myObject = JSON.parse(localStorage.getItem('myObject')) || {
first : $scope.people.first,
last : $scope.people.last,
};
$scope.update = function(){
$scope.people.first = $scope.myObject.first;
$scope.people.last = $scope.myObject.last;
localStorage.setItem('myObject', JSON.stringify($scope.myObject));

};

$scope.deletePeople = deletePeople;
function deletePeople(id){
var userToDelete;
$scope.people.forEach(function(p, index){
if(p.id == id){
userToDelete = index;
}
});
$scope.people.splice(userToDelete, 1);
console.log($scope.people);
}

});

用户列表

<div class="people" ng-repeat="p in people | filter:userSearch" >
<a href="#/people/{{ p.id }}">
<img ng-src="{{p.img}}"/>
<span class="name">{{p.first}} </span>
<span class="name">{{p.last}} </span>
<p class="title">{{p.title}} </p>
<span class="date">{{p.date}} </span>
</a>
</div> 

人员视图部分应包含在div<div ng-controller="MyCtrl">下。因此,只需将该行向上移动,使其成为代码的第一行。

表单中的 ng 模型需要分别是 people.first 和 people.last。 例如<b>First Name:</b> <input type="text" ng-model="people.first"> <br> <b>Last Name:</b> <input type="text" ng-model="people.last">

检查这个

正如 Swailem95 所说,您必须将<div ng-controller="MyCtrl">顶部移动,之后如下所示。

<div ng-controller="MyCtrl">
<div class="people-view">
<h2 class="name">{{people.first}}</h2>
<h2 class="name">{{people.last}}</h2>
<span class="title">{{people.title}}</span>
<span class="date">{{people.date}} </span>
</div>
<!-- the form -->
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="myObject.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="myObject.last">
</fieldset>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="update()">Update</button>
</form>
</div>
</div>

最新更新