각도 지연 방법JS 인스턴트 검색?
을 사용하다만, 각각 조금 .keyup().
JS:
var App = angular.module('App', []);
App.controller('DisplayController', function($scope, $http) {
$http.get('data.json').then(function(result){
$scope.entries = result.data;
});
});
HTML:
<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:searchText">
<span>{{entry.content}}</span>
</div>
JSON 데이터는 그렇게 크지도 않고, 300KB 밖에 되지 않기 때문에, 각 키 입력에 조작을 하는 것이 아니라, 검색의 지연을 1초 정도 두고, 유저가 입력을 완료할 때까지 기다리는 것이 좋다고 생각합니다.각진JS는 내부적으로 이것을 하고 있는데, 여기에서 문서나 다른 토픽을 읽어본 결과, 구체적인 답을 찾을 수 없었습니다.
즉시 검색을 지연시킬 수 있는 방법이 있다면 알려주시면 감사하겠습니다.
갱신하다
이제 어느 때보다 쉬워졌습니다(Angular 1.3). 모델에 데바운스 옵션만 추가하면 됩니다.
<input type="text" ng-model="searchStr" ng-model-options="{debounce: 1000}">
다음 중 하나:
http://plnkr.co/edit/4V13gKhttpplnkr.co/edit/
:ngModelOptions " " :
https://docs.angularjs.org/api/ng/directive/ngModelOptionshttpsdocs.angularjs.org/api/ng/directive/
이전 방법:
여기 각도 자체 이상의 종속성이 없는 또 다른 방법이 있습니다.
타임아웃을 설정하고 현재 스트링을 이전 버전과 비교해야 합니다.두 문자열이 동일한 경우 검색이 수행됩니다.
$scope.$watch('searchStr', function (tmpStr)
{
if (!tmpStr || tmpStr.length == 0)
return 0;
$timeout(function() {
// if searchStr is still the same..
// go ahead and retrieve the data
if (tmpStr === $scope.searchStr)
{
$http.get('//echo.jsontest.com/res/'+ tmpStr).success(function(data) {
// update the textarea
$scope.responseData = data.res;
});
}
}, 1000);
});
다음과 같이 표시됩니다.
<input type="text" data-ng-model="searchStr">
<textarea> {{responseData}} </textarea>
필수 plunker:http://plnkr.co/dAPmwf
(Angular 1.3 용액은 아래 답변을 참조하십시오.)
여기서의 문제는 모델이 변경될 때마다 검색이 실행된다는 것입니다. 즉, 입력에 대한 모든 키 조작입니다.
이를 위해서는 보다 깔끔한 방법이 있지만 아마도 가장 쉬운 방법은 필터가 동작하는 컨트롤러 내에서 $scope 속성이 정의되도록 바인딩을 전환하는 것입니다.그러면 $scope 변수가 업데이트되는 빈도를 제어할 수 있습니다.다음과 같은 경우:
JS:
var App = angular.module('App', []);
App.controller('DisplayController', function($scope, $http, $timeout) {
$http.get('data.json').then(function(result){
$scope.entries = result.data;
});
// This is what you will bind the filter to
$scope.filterText = '';
// Instantiate these variables outside the watch
var tempFilterText = '',
filterTextTimeout;
$scope.$watch('searchText', function (val) {
if (filterTextTimeout) $timeout.cancel(filterTextTimeout);
tempFilterText = val;
filterTextTimeout = $timeout(function() {
$scope.filterText = tempFilterText;
}, 250); // delay 250 ms
})
});
HTML:
<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:filterText">
<span>{{entry.content}}</span>
</div>
Angular 1.3에서는 다음과 같이 합니다.
HTML:
<input ng-model="msg" ng-model-options="{debounce: 1000}">
컨트롤러:
$scope.$watch('variableName', function(nVal, oVal) {
if (nVal !== oVal) {
myDebouncedFunction();
}
});
는 angular에게 말합니다.myDebouncedFunction() 경우,msg스코프 변수가 변경됩니다. '''ng-model-options="{debounce: 1000}" msg1번입니다.
<input type="text"
ng-model ="criteria.searchtext""
ng-model-options="{debounce: {'default': 1000, 'blur': 0}}"
class="form-control"
placeholder="Search" >
이제 ng-model-options debounce를 시간과 함께 설정할 수 있으며, 흐릿해지면 모델을 즉시 변경해야 합니다.그렇지 않으면 저장 시 지연이 완료되지 않으면 오래된 값이 됩니다.
HTML 마크업에서 키업/키다운을 사용하는 사용자용.이것은 시계를 사용하지 않는다.
JS
app.controller('SearchCtrl', function ($scope, $http, $timeout) {
var promise = '';
$scope.search = function() {
if(promise){
$timeout.cancel(promise);
}
promise = $timeout(function() {
//ajax call goes here..
},2000);
};
});
HTML
<input type="search" autocomplete="off" ng-model="keywords" ng-keyup="search()" placeholder="Search...">
angularjs 모델 갱신 프로그램 공개/제한:http://jsfiddle.net/lgersman/vPsGb/3/
이 경우 다음과 같이 jsfiddle 코드의 디렉티브를 사용하는 것 외에 할 일은 없습니다.
<input
id="searchText"
type="search"
placeholder="live search..."
ng-model="searchText"
ng-ampere-debounce
/>
기본적으로는 http://benalman.com/projects/jquery-throttle-debounce-plugin/을 사용하여 "ng-ampere-contains"라는 이름의 단일 각도 지시어로 구성된 작은 코드 조각이며, 모든 돔 요소에 연결할 수 있습니다.디렉티브는 이벤트 조절 시기를 제어할 수 있도록 연결된 이벤트 핸들러의 순서를 변경합니다.
슬롯링/디버깅*모델 각도 업데이트* 각도 이벤트핸들러 ng-[이벤트]* jquery 이벤트핸들러에 사용할 수 있습니다.
여기를 봐주세요.http://jsfiddle.net/lgersman/vPsGb/3/
이 지시는 Orangevolt Ampere 프레임워크(https://github.com/lgersman/jquery.orangevolt-ampere)의 일부입니다.
여기서 리다이렉트된 사용자만:
에서 소개한 바와 같이Angular 1.3ng-model-model Atribute를 사용할 수 있습니다.
<input
id="searchText"
type="search"
placeholder="live search..."
ng-model="searchText"
ng-model-options="{ debounce: 250 }"
/>
이 문제를 해결하는 가장 좋은 방법은 Ben Alman의 플러그인 jQuery throttle/debounce를 사용하는 것이라고 생각합니다.제 생각에 당신의 폼에서 모든 분야의 이벤트를 지연시킬 필요는 없습니다.
$scope를 포장해 주세요.$.watch 처리 함수는 다음과 같습니다.
$scope.$watch("searchText", $.debounce(1000, function() {
console.log($scope.searchText);
}), true);
또 다른 해결책은 모델 업데이트에 지연 기능을 추가하는 것입니다.이 단순한 지시가 요령을 부리는 것 같습니다.
app.directive('delayedModel', function() {
return {
scope: {
model: '=delayedModel'
},
link: function(scope, element, attrs) {
element.val(scope.model);
scope.$watch('model', function(newVal, oldVal) {
if (newVal !== oldVal) {
element.val(scope.model);
}
});
var timeout;
element.on('keyup paste search', function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
scope.model = element[0].value;
element.val(scope.model);
scope.$apply();
}, attrs.delay || 500);
});
}
};
});
사용방법:
<input delayed-model="searchText" data-delay="500" id="searchText" type="search" placeholder="live search..." />
그래서 너는 그냥delayed-model대신해서ng-model원하는 것을 정의합니다.data-delay.
데모: http://plnkr.co/edit/OmB4C3jtUD2Wjq5kzTSU?p=preview
이 문제를 해결했습니다.기본적으로 디렉티브에서 감시하는 특별한 Atribut에 실제 ng-model을 바인드하고 debounce 서비스를 사용하여 디렉티브Atribute를 갱신하여 사용자가 ng-model이 아닌 debounce-model에 바인드하는 변수를 감시합니다.
.directive('debounceDelay', function ($compile, $debounce) {
return {
replace: false,
scope: {
debounceModel: '='
},
link: function (scope, element, attr) {
var delay= attr.debounceDelay;
var applyFunc = function () {
scope.debounceModel = scope.model;
}
scope.model = scope.debounceModel;
scope.$watch('model', function(){
$debounce(applyFunc, delay);
});
attr.$set('ngModel', 'model');
element.removeAttr('debounce-delay'); // so the next $compile won't run it again!
$compile(element)(scope);
}
};
});
사용방법:
<input type="text" debounce-delay="1000" debounce-model="search"></input>
컨트롤러 내:
$scope.search = "";
$scope.$watch('search', function (newVal, oldVal) {
if(newVal === oldVal){
return;
}else{ //do something meaningful }
jsfiddle 데모:http://jsfiddle.net/6K7Kd/37/
$http://http://jsfiddle.net/Warspawn/6K7Kd/ 에서 $http://http://jsfiddle.net/Warspawn/6K7Kd/ 를 참조할 수 있습니다.
최종 Bind 디렉티브에서 영감을 얻어 http://jsfiddle.net/fctZH/12/
Angular 1.3은 ng-model-options debounce를 가지지만, 그 전까지는 Josue Ibarra가 말한 것처럼 타이머를 사용해야 합니다.하지만, 그의 코드에서 그는 모든 키를 누를 때마다 타이머를 작동시킨다.또한 Angular에서 $timeout을 사용하거나 setTimeout 종료 시 $apply를 사용해야 하는 경우 setTimeout을 사용하고 있습니다.
왜 다들 시계를 쓰려고 하죠?다음 함수를 사용할 수도 있습니다.
var tempArticleSearchTerm;
$scope.lookupArticle = function (val) {
tempArticleSearchTerm = val;
$timeout(function () {
if (val == tempArticleSearchTerm) {
//function you want to execute after 250ms, if the value as changed
}
}, 250);
};
하거나 한 번 하는 것이라고 합니다.$dirty하면 추가 콜을 할 수 로드되어 빠릅니다.이렇게 하면 추가 http 콜을 절약할 수 있고 데이터가 미리 로드되어 있으면 훨씬 빠릅니다.기억은 아프겠지만 그만한 가치가 있어요.
언급URL : https://stackoverflow.com/questions/15304562/how-to-put-a-delay-on-angularjs-instant-search
'programing' 카테고리의 다른 글
| 스프링은 @Autowired Annotation 없이 생성자에 종속성을 주입합니다. (0) | 2023.03.21 |
|---|---|
| sqlplus에서 "PL/SQL procedure successfully completed" 메시지를 표시하지 않으려면 어떻게 해야 합니까? (0) | 2023.03.21 |
| $http가 요청으로 쿠키를 보내지 않음 (0) | 2023.03.16 |
| Spring Security anonymous 403 대신 401 (0) | 2023.03.16 |
| Jquery - Uncarched TypeError: 'in' 연산자를 사용하여 다음 위치에서 '324'를 검색할 수 없습니다. (0) | 2023.03.16 |