我有一个显示列表(搜索输入的结果)的页面。
我正在使用 ng-model
来捕获输入文本:ng-model="search_text"
。
问题是每次模型有内容时我都想自动滚动到包含列表的 div。如果它是空的,它应该什么都不做,但如果在 search_text
中写了一些东西,它应该会起作用并自动向下滚动到列表结果。
最佳答案
你可以用一个简单的指令来实现这个 demo fiddle 强>。它使用 $anchorScroll()
实现自动滚动功能。
查看
<div ng-controller="MyCtrl">
<input ng-model="searchText" type="text">
<div id="list" auto-scroller id-to-scroll-to="'list'" trigger="searchText">
My List
</div>
</div>
AngularJS 应用程序/指令
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {});
myApp.directive('autoScroller', function ($location, $anchorScroll, $timeout) {
return {
restrit: 'A',
scope: {
trigger: '=',
idToScrollTo: '='
},
link: function (scope, element, attrs) {
scope.$watch('trigger', function (newValue, oldValue) {
if (newValue && newValue !== oldValue) {
$timeout(function () {
$location.hash(scope.idToScrollTo);
$anchorScroll();
});
}
});
}
}
});
关于javascript - 如果 ng-model 为真 AngularJS 则滚动到元素 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46168069/