gpt4 book ai didi

javascript - 孤立范围内的清晰形式?

转载 作者:行者123 更新时间:2023-11-28 01:24:32 24 4
gpt4 key购买 nike

我在一个 ionic 应用程序中有一个用于评论的文本输入,并且在提交表单时需要清除它。

我有一个 ionic 模态内的表格,所以我假设我是一个孤立范围的受害者,但是,表格仍然需要清除..这是我的 Controller (我已经标记了我试图清除的地方形式):

.controller('EasternInnerCtrl', function ($http, $timeout, $scope, $ionicLoading, $stateParams, $ionicScrollDelegate, $cordovaSocialSharing, $ionicModal, Easternc, AuthService) {
$scope.eastc = Easternc.get($stateParams.eastcId);

$ionicModal.fromTemplateUrl('commenter.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal
})

$scope.openModal = function() {
$scope.modal.show();
}

$scope.closeModal = function() {
$scope.modal.hide();
};

$scope.$on('$destroy', function() {
$scope.modal.remove();
});




$scope.addComment = function(new_comment, comments){
Easternc.submitComment($scope.eastc.id, new_comment, comments).then(function(data){
if(data.status=="ok"){
var user = AuthService.getUser();

var comment = {
author: {name: user.data.username},
content: new_comment,
date: Date.now(),
user_gravatar : user.avatar,
id: data.comment_id
};

$scope.eastc.comments.push(comment);

$scope.new_comment = ""; // HERE IS WHERE I AM TRYING TO CLEAR THE FORM

$scope.new_comment_id = data.comment_id;
}
});
};

})

最佳答案

您对作用域问题的怀疑是正确的,尽管在这种情况下是因为子作用域而不是孤立作用域。

解决这个问题的最简单(也是最好)的方法是使用“点”表示法,这样您尝试访问和清除的属性在表单和 Controller 中将是相同的。

因此,与其使用 $scope.new_comment,不如创建一个对象,然后使用该对象。

例如在您的 Controller 中首先设置值:

$scope.new_comment_form = {
content: ""
};

然后在你的表单 html 中你可以使用

<input type="text" ng-model="new_comment_form.content">

最后当你想清除它时,只需清除对象内部的值即可:

$scope.eastc.comments.push(comment);

// clear like this
$scope.new_comment_form.content = "";

$scope.new_comment_id = data.comment_id;

在这里,我使用与上面相同的代码大纲创建了一个示例工作 plnkr。它从新文件加载模态,在您执行 addComment 后,它“保存”评论并清除表单:http://plnkr.co/edit/s6CdQN?p=preview

有关使用点符号的更多信息以及使用它的原因,请参阅以下链接: https://github.com/angular/angular.js/wiki/Understanding-Scopes Why don't the AngularJS docs use a dot in the model directive? What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

关于javascript - 孤立范围内的清晰形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32648069/

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