加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

角度全局搜索框

发布时间:2020-12-17 07:16:20 所属栏目:安全 来源:网络整理
导读:我想实现一个搜索框,根据正在使用的控制器更改搜索内容.如果您在“帖子”视图中,它将搜索帖子api,如果您在视频视图中,则会搜索视频api.似乎搜索框可能需要自己的控制器.我很确定我需要在所有模型控制器中注入搜索服务,但我不确定如何更改搜索的URL或将输入绑
我想实现一个搜索框,根据正在使用的控制器更改搜索内容.如果您在“帖子”视图中,它将搜索帖子api,如果您在视频视图中,则会搜索视频api.似乎搜索框可能需要自己的控制器.我很确定我需要在所有模型控制器中注入搜索服务,但我不确定如何更改搜索的URL或将输入绑定到不同的控制器范围.

那么任何想法如何让一个全局搜索框根据哪个控制器正在使用它来改变搜索位置并将其状态恢复到不断变化的视图?

解决方法

要创建一个资源调用动态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>

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);
        });


    }

})

每个显示结果的子控制器.

.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',data) {
        $scope.videos = data;
    });

})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读