要创建一个资源调用动态API,我将首先创建两个映射到您的两个端点,帖子和视频的$资源.然后在全局搜索上放置一个ng-change事件,该事件调用基本控制器中的函数.
这个函数首先需要弄清楚要搜索的api.然后进行适当的api调用.重要的部分是回调,我认为这正是你要找的.在回调中,您可以从api查询中广播resp数据.您的每个控制器都将使用$ on函数监听事件.然后,侦听器将使用回调数据填充正确的范围变量.
伪下面.
与ng-change相同的html布局
<html>
<body ng-controller="AppController">
<form>
<label>Search</label>
<input ng-model="global.search" ng-change="apiSearch()" type="text" class="form-control" />
</form>
<div ui-view="posts">
<div ng-controller="PostController">
<p ng-repeat="post in posts | filter: global.search">{{ post.name }}</p>
</div>
</div>
<div ui-view="videos">
<div ng-controller="VideoController">
<p ng-repeat="video in videos | filter: global.search">{{ video.name }}</p>
</div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
AppController的
.controller('AppController', function ($scope, PostService, VideoService) {
$scope.apiSearch = function() {
// Determine what service to use. Could look at the current url. Could set value on scope
// every time a controller is hit to know what your current controller is. If you need
// help with this part let me know.
var service = VideoService, eventName = 'video';
if ($rootScope.currentController == 'PostController') {
service = PostService;
eventName = 'post';
}
// Make call to service, service is either PostService or VideoService, based on your logic above.
// This is pseudo, i dont know what your call needs to look like.
service.query({query: $scope.global.search}, function(resp) {
// this is the callback you need to $broadcast the data to the child controllers
$scope.$broadcast(eventName, resp);
});
}
})
Run Code Online (Sandbox Code Playgroud)
每个显示结果的子控制器.
.controller('PostController', function($scope) {
// anytime an event is broadcasted with "post" as the key, $scope.posts will be populated with the
// callback response from your search api.
$scope.$on('post', function(event, data) {
$scope.posts = data;
});
})
.controller('VideoController', function($scope) {
$scope.$on('video', function(event, data) {
$scope.videos = data;
});
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13941 次 |
| 最近记录: |