角度全局搜索框

chr*_*ris 5 service search angularjs

我想实现一个搜索框,根据正在使用的控制器更改搜索内容.如果您在"帖子"视图中,它将搜索帖子api,如果您在视频视图中,则会搜索视频api.似乎搜索框可能需要自己的控制器.我很确定我需要在所有模型控制器中注入搜索服务,但我不确定如何更改搜索的URL或将输入绑定到不同的控制器范围.

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

j_w*_*dev 9

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