[英]Angular.js and server-side search - how to, best practices
在我的应用程序中,我有一个简单的angular.js过滤器,它运行良好,但是现在我需要集成服务器端搜索。 我为此设置了端点,并创建了指令,该指令监视输入中的查询并向服务器返回结果请求:
HTML:
<search ng-model="query"></search>
JS:
...
restrict: 'E',
scope: {
ngModel: '='
},
template: '<input type="text" ng-model="ngModel" />',
link: function (scope, elem, attrs) {
var timer = false;
scope.$watch('ngModel', function (value) {
if (timer) {
$timeout.cancel(timer);
}
timer = $timeout(function () {
if (value) {
scope.$parent.items = rest.query({ resource: 'search', query: value });
}
}, 1000);
});
}
...
但是,问题在于范围 。 如您所见,我正在将结果写入父范围项,因为我需要搜索结果保持在同一控制器的同一页面上(就像在客户端过滤器中一样):
几个控制器和搜索结果的通用模板:
<ul class="items">
<li class="item item{{$index+1}}" ng-repeat="item in items">
...
</li>
</ul>
因此,在表示服务器端搜索查询的结果之后,在清除输入字段时,我需要以某种方式返回搜索之前表示的所有项目,并且目前无法为此找到最佳解决方案。
也许有人之前做了类似的事情?
不知道这是否是一个好方法,但是我有一个指令列出学生(可以选择修读一门课程),该指令从工厂获取数据,而工厂又使用$resource
来获取数据。 摆弄着它,就像我之前说过的,不确定这是否是正确的方法。
似乎可以正常工作,所以我在这里发布了代码。
模板/partials/v001/student-course-list.html
:
Search: <input data-ng-model="query" data-ng-change="search()"/>
Only for this course <input type="checkbox" name="courseid"
data-ng-model="courseid" data-ng-change="search()">
指令:
// list students (optional for course) both students and course
// are initially set outside and passed through
angular.module('student').directive('studentCourseList',
['dataProvider',
function(dataProvider) {
return {
restrict: 'A',
//static in GAE so will be cached for a year
// need versioning
templateUrl: '/partials/v001/student-course-list.html',
scope: {
course: '=',
students: '='
},
link: function(scope, elem, attrs) {
scope.search = functions.searchStudentsByName(
dataProvider, scope);
}
};
}
]);
功能:
//Containing controllers/directives DOM event handlers
// Like ng-change for the search box and isInCourse checkbox
var functions = {
searchStudentsByName: function(dataProvider, scope) {
return function() {
//half a second delay before starting search
// user may be typing several characters
clearTimeout(scope.timeoutId);
scope.timeoutId = setTimeout(function() {
var sId=(scope.courseid)?scope.course.id:false,
q=(scope.query)?scope.query:"";
//can check q again if len<2 set it to ""
// this because isInCourse may have triggered this
scope.students=dataProvider.searchStudentsByName(
scope.query, sId);
}, 500);
};
}
};
工厂(称为dataProvider)在返回承诺并解决承诺之前使用$ q,但是似乎使用$ resource可以仅返回$ resource,并且返回结果时数据将绑定。
angular.module('dataProvider', []).
factory('dataProvider', ['$resource','$q',function($resource,$q) {
//Anything having /app/student/ goes to google app server
// prefer to just add getstring on the url
var StudentFromApp = $resource('/app/student/',
{}
);
return {
//course id is optional in case only student for course
searchStudentsByName:function(sName,cid){
return StudentFromApp.query(
{courseid:cid,studentName:sName});
}
};
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.