表单不是从带有角度的休息响应填充的

Form is not populated from rest response with angular

本文关键字:响应 填充 表单      更新时间:2023-09-26

我是AngularJS的新手,我对它有点困惑。我必须做一个包含一些配置选项的页面,我想保存这些选项,当我再次打开页面时,必须使用保存的值填充输入。我有一个复选框,当它的值为 false 时,所有其他字段都被禁用。我进行了保存并且它可以工作,但是当我之后加载页面时,输入被禁用且为空。我正在ng-init上做GET请求,而不是设置每个输入的范围变量。它们保持禁用状态,即使响应将此复选框的 ng-model 设置为 true,也不会选中该复选框。ng-check是相同的,不可见。当我选中复选框时,神奇地,这些值以正确的值可见。这是 html。

<div ng-controller="archivingController" ng-init="getArchivingOptions()">
<form name="archivingForm" ng-submit="saveConfiguration()" novalidate>
    <div id="archivingFormEnable">
        <input type="checkbox" class="checkbox" ng-model="configurations.enableArchiving"/>
        <label id="archivingLabelEnable">Enable Archiving</label>
    </div>
    <fieldset>
        <legend>Archiving Settings</legend>
        <div id="globalArchivingDiv">
            <label id="globalArchivingLabel" style="width: 240px">Global archiving:</label>
            <select ng-init="configurations.globalArchiving='disabled'" ng-model="configurations.globalArchiving" ng-disabled="!configurations.enableArchiving">
                <option value="disabled">Disabled</option>
                <option value="enabled">Enabled</option>
            </select>
        </div>
        <div id="archiveFolderDiv">
            <label id="archiveFolderLabel">Archive folder:</label>
            <input type="text" ng-disabled="!configurations.enableFileArchiving" ng-model="configurations.archiveFolder" required/>
            <span ng-show="fileArchivingForm.archiveFolder.$invalid && configurations.enableFileArchiving">Required.</span>
        </div>
    </fieldset>
    <button id="save" ng-disabled="fileArchivingForm.$invalid && configurations.enableFileArchiving">Save</button>
</form>
</div>

还有控制器。

mainApp.controller('archivingController', ['$scope', function($scope){
$scope.getArchivingOptions = function(){
    $.ajax({
        url: someURL,
        type: 'GET',
        dataType : 'json', 
        cache: false,
        success : function(data) { 
            $scope.configurations = data.configurations;
        }
    });
}
$scope.saveConfiguration = function(){
    $.ajax({
        type : 'POST',
        contentType : 'application/json',
        url : someURL,
        dataType : 'json',
        data : JSON.stringify($scope.configurations),
        complete : function(jqXHR, textStatus) {
            //some msg
        }
    });     
}
}]);

实际上,我确定所有这些都已设置,因为当我打电话时 console.log($scope.configurations.archiveFolder);打印的值与响应中的值正确。问题是在我单击复选框之前它不可见。我不知道该怎么办。我愿意接受建议。提前谢谢你。

如果你使用 jquery 的 $.ajax 而不是 angular 的 $http,你需要将回调包装在 $scope.$apply 中:

"success": function(data) {
   $scope.$apply(function() {
       //your code here
   });
}