我正在遵循Django和Angular开发的Pluralsight课程。我对这两个框架都非常陌生,但有使用其他语言和框架的经验。
在课程中,我们展示了如何将debounce
用作带有在ng-change
期间调用的函数的选项。此函数update
使用http.put
将放置请求发送到本地 REST API。
但是,使用以前的语言后,使用ng-change
向Web服务发送请求(即使debounce
设置为500)的想法似乎是一个非常愚蠢的想法,因为会有很多不必要的流量被发送到服务。
如何才能做得更好?我试图在按钮上设置ng-click
以触发update
,但由于某种原因,它似乎没有触发事件......
代码中缺少去抖动,因为我根本不确定是否应该使用这种方法。
编辑:
正如其中一个答案中提到的,如果我正在通过自动更正/填充进行某种控制搜索,那么使用ng-keyup
可能是一个好主意,但在这种情况下,我担心使用ng-keyup
或ng-change
在数据库中提交(更新)具有put
请求的数据会产生太多开销流量。
卡.html
<div class="card" ng-hide="edit" ng-click="edit=true">
<h4> {{ card.title }} </h4>
<span class="description"> {{ card.description }} </span>
</div>
<div class="card" ng-show="edit">
<div class="flex">
<label><strong>Title: </strong></label>
<input type="text" ng-model="card.title"
ng-change="update()" />
</div>
<textarea ng-model="card.description"
ng-change="update()"
placeholder="Enter description here..."></textarea>
<button ng-click="edit=false">Close</button>
</div>
卡指令.js:
(function () {
"use strict";
angular.module('scrumboard.demo')
.directive('scrumboardCard', CardDirective);
function CardDirective() {
return {
templateUrl: "/static/scrumboard/card.html",
restrict: 'E',
controller: ['$scope', '$http', function ($scope, $http) {
let url = '/scrumboard/cards/' + $scope.card.id + '/';
console.log("Inside");
$scope.update = function() {
console.log("I'm inside");
$http.put(url, $scope.card)
.finally(function() {
edit = false;
});
};
}]
};
}
})();
通常在文本搜索中,建议使用ngKeyup
而不是 ng-change,
<textarea ng-model="card.description"
ng-keyup="update()"
placeholder="Enter description here..."></textarea>