AngularJS:在看跌过程中采用旧值而不是新值

AngularJS: Taking old values instead of new during put

本文关键字:新值 过程中 AngularJS      更新时间:2023-09-26
更新

时,我想插入来自 ui 的新值,而不是本地集合中存在的旧值。下面的代码在本地集合中插入旧值(我不希望这种情况发生)。

dataService.getSupplierById($routeParams.id)
.then(function (supplier) {
    $scope.supplier = supplier; //now this contains local collection
    $scope.save = function () {
        $scope.updatedSupplier = $scope.supplier; //I want the scope to be updated and take values from the ui
        dataService.updateSupplier($routeParams.id, $scope.updatedSupplier)
        .then(function () {
            //success
        },
            function () {
                //error
            });
    };
},
function () {
    //error
});

这是我的 Html。

<div>
    <label for="City">City</label>
    <input name="City" type="text" data-ng-model="updateSupplier.city" value="{{supplier.city}}" />
</div>

我该怎么做?如何更新范围以采用新值?我是棱角刚开始的。

如果要绑定到 updateSupplier 作为ng-model,则在保存时不应覆盖这些值:

$scope.save = function () {
    // remove the line that overwrites, was here    
    dataService.updateSupplier($routeParams.id, $scope.updatedSupplier)
        .then(function () {
            //success
        },
        function () {
            //error
        });
    };
}

Angular 将负责ng-model内值的双向绑定,因此在您保存时,它将具有在文本框中输入的正确值。

您还可以通过不使用 2 个不同的范围属性来清理代码:

dataService.getSupplierById($routeParams.id)
.then(function (supplier) {
    $scope.supplier = supplier; //now this contains local collection
    $scope.save = function () {
        dataService.updateSupplier($routeParams.id, $scope.supplier )
        .then(function () {
            //success
        },
            function () {
                //error
            });
    };
},
function () {
    //error
});

然后在 html 中:

<div>
    <label for="City">City</label>
    <input name="City" type="text" data-ng-model="supplier.city" />
</div>

初始值应自动绑定到 value 属性中。