gpt4 book ai didi

javascript - ng-if 中丢失的表单功能

转载 作者:行者123 更新时间:2023-11-29 21:39:02 24 4
gpt4 key购买 nike

我有一个带有复选框的简单表单,单击该复选框可从对象中删除属性。

这是 Controller :

app.controller('PropController', function ($scope) {
var str = '{"meta":{"aprop":"lprop"},"props":{"gprop":12,"lprop":9,"wrop":5}}';
$scope.filecontent = JSON.parse(str);
$scope.delprop = false;
$scope.propobj = $scope.filecontent.props;
$scope.proptodel = $scope.filecontent.meta.prop;
var mainvalue = $scope.propobj[$scope.proptodel];
$scope.$watch('delprop', function () {
if ($scope.delprop == true) {
delete $scope.propobj[$scope.proptodel];
} else {
$scope.propobj[$scope.proptodel] = mainvalue;
}
});

和 View :

<div ng-app="SomeProperties" ng-controller="PropController">

<div ng-if="proptodel">
there is a property to delete: {{proptodel}}
<form><input type="checkbox" ng-model="delprop"></form>
filecontent: {{filecontent}}
</div>

<div ng-if="!proptodel">
there is NO property to delete
</div>

</div>

The app on jsfiddle.

当表单在 ng-if 中时出现问题,它停止运行。正如您可以在 jsfiddle 中尝试的那样,当我从包含表单的 div 中删除 ng-if="proptodel" 时,它工作正常。对此有何解释?

最佳答案

您需要将 delprop 放入对象中才能使 ng-model 正常工作。这意味着你的标记应该有:

<form><input type="checkbox" ng-model="obj.delprop"></form>

你的 Javascript 代码应该是这样的:

$scope.obj = {
delprop: false
};

$scope.propobj = $scope.filecontent.props;
$scope.proptodel = $scope.filecontent.meta.prop;
var mainvalue = $scope.propobj[$scope.proptodel];
$scope.$watch('obj.delprop', function () {
if ($scope.obj.delprop == true) {
delete $scope.propobj[$scope.proptodel];
} else {
$scope.propobj[$scope.proptodel] = mainvalue;
}
});

当然你应该为对象找到一个合适的名称,因为 obj 真的很糟糕而且很通用;-)

关于javascript - ng-if 中丢失的表单功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33777364/

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