在我的应用程序中,我有简单的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>
因此,在表示服务器端搜索查询的结果后,当清除输入字段时,我需要以某种方式返回搜索前表示的所有项目,目前无法找到最佳解决方案..
也许有人之前做过类似的事情?
答案 0 :(得分:2)
不确定这是否是一个很好的方法,但我已经有一个指令列出学生(可选择一门课程)从工厂获取数据,而工厂又使用$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返回一个promise并解决它,但似乎使用$ 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});
}
};
}]);