我有一些 ng-repeat
<tr ng-repeat="Picture in Pictures">
<td>{{Picture.Id}}</td>
<td>
<div ng-hide="Picture.editorEnabled">
{{Picture.Name}}
</div>
<div ng-show="Picture.editorEnabled">
<input ng-model="Picture.editName" class="form-control" ng-show="Picture.editorEnabled">
</div>
</td>
<td>
<button type="button" name="editButton" class="btn btn-warning" ng-hide="Picture.editorEnabled"
ng-click="enableEditor(Picture)">Edit
</button>
<div ng-show="Picture.editorEnabled">
<button type="button" name="saveEditButton" class="btn btn-success"
ng-click="saveEditor(editName,editImageUrl,Picture)">Save
</button>
<button type="button" name="cancelEditButton" class="btn btn-warning" ng-click="disableEditor(Picture)">
Cancel
</button>
</div>
</td>
</tr>
这是我的 Controller 代码:
$scope.enableEditor = function(picture) {
picture.editorEnabled = true;
picture.editName = picture.Name;
picture.editImageUrl = picture.ImageUrl;
};
$scope.disableEditor = function(picture) {
picture.editorEnabled = false;
picture.editName = null;
picture.editImageUrl = null;
};
$scope.saveEditor = function(name, url, picture) {
$.ajax({
url: 'admin/pictures/edit/' + picture.Id,
type: 'POST',
data: {
ImageUrl: url,
Name: name
},
success: function() {
picture.Name = picture.editName;
picture.ImageUrl = picture.editImageUrl;
$scope.disableEditor(picture);
}
});
};
当我单击“编辑”时,会出现编辑字段和保存、取消按钮。
当我点击“取消”时,它消失了。
当我单击“保存”字段保存到数据库时,方法 disableEditor
在同一对象上执行,我检查了 Id
属性,并且在调试器中它显示 editorEnabled
是错误的,但在我的浏览器中仍然存在保存、取消按钮和用于编辑的字段。我再次点击“保存”,它消失了。
最佳答案
您应该尝试使用 $http
而不是 $.ajax
。 jQuery 的 $.ajax
在 Angular 的范围之外执行。回调中的任何代码都不会反射(reflect)在您的作用域中,因为这发生在 Angular 的摘要周期之外。请尝试以下操作:
var url = 'admin/pictures/edit/' + picture.Id;
var data = $httpParamSerializerJQLike({
ImageUrl: url,
Name: name
});
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
$http.post(url, data, config).then(function() {
picture.Name = picture.editName;
picture.ImageUrl = picture.editImageUrl;
$scope.disableEditor(picture);
});
为此,您需要将 $http
和 $httpParamSerializerJQLike
服务注入(inject)您的 Controller 。我假设您需要将其作为表单提交,因为这是默认情况下 $.ajax
的工作方式。这需要 Angular 1.4+。
请注意,虽然可以使用 $.ajax
然后将您的成功代码包装在 $timeout
或 $scope.$apply()
,你最好使用 Angular 自己的 $http
。
关于javascript - angularjs ng-show 绑定(bind)不适用于 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32925151/