Create search articles feature in MEAN stack

风流意气都作罢 提交于 2019-12-08 05:24:39

问题


First of all, let me tell you that I'm a novice in the world of javascript and node.js. I have been searching for help in trying to do what i want but haven't found yet.

I am using the MEAN stack(http://mean.io/) and I am trying to implement a search feature in the included articles model. The search would look for articles with a specific tag and would be implemented in the index page. Follow me and see if you can find what I am missing please.

In the backend:

app/models/

/**
 * Article Schema
 */
var ArticleSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    title: {
        type: String,
        default: '',
        trim: true
    },
    content: {
        type: String,
        default: '',
        trim: true
    },
    tag: {
        type: String,
        default: '',
        trim: true
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    }
});

app/controllers/

exports.searcharticle = function(req, res) {
    Article.find({'tag': req.params.tag}).sort('-created').populate('user', 'name username').exec(function(err, articles) {
        if (err) {
            res.render('error', {
                status: 500
            });
        } else {
            res.jsonp(articles);
        }
    });
};

Added the route for the search in app/routes/articles.js

app.get('/articles/search/:tag', articles.searcharticle);

In the frontend:

Created the view for the search wich will display the search results - public/views/articles/search.html

<section data-ng-controller="ArticlesController" data-ng-init="searchart()">
<ul class="articles unstyled">
<li data-ng-repeat="article in articles">
<span>{{article.created | date:'medium'}}</span> /
<span>{{article.user.name}}</span>
<h2><a data-ng-href="#!/articles/{{article._id}}">{{article.name}}</a></h2>
<div>{{article.tag}}</div>
</li>
</ul>
<h1 data-ng-hide="!articles || articles.length">Your search hasn't returned any results. <br> Why don't you <a href="/#!/articles/create">Create One</a>?</h1>
</section>

The view for the index.html, where the searchbox will be implemented

<section data-ng-controller="ArticlesController">
      <form role="form" data-ng-submit="searchart()">
        <div>
          <div>
            <input type="text" id="tag" ng-model="selected" class="form-control" placeholder="Tag">
          </div>
          <div>
            <button type="submit" class="btn btn-default">Submit</button>
          </div>
        </div> 
      </form>

Added the route to the config.js

when('/articles/search/:tag', {
            templateUrl: 'views/articles/search.html'
        }).

And added the search function to the articles controller

$scope.searchart = function() {
    Articles.query(function(articles) {
        $scope.articles = articles;
    });
};

Right now, with this code implemented, when I click in the submit button in the index page, nothing happens.

Can you find what am I missing?

Thanks in advance!


回答1:


In order to use a URL in your client Article Service, you should define the URL Parameter in the articles service at: packages/articles/public/services/article.js, like the articleId parameter already defined in there like this:

angular.module('mean.articles').factory('Articles', ['$resource',
  function($resource) {
    return $resource('articles/:articleId', {
      articleId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
]);

Then you need to pass it in your angular controller search method, like the function that gets one by id, like this:

$scope.findOne = function() {
      Articles.get({
        articleId: $stateParams.articleId
      }, function(article) {
        $scope.article = article;
      });
    };

Personally I don't know how to add another parameter to the $resource object in addition to the existing one (articleId), you may have to create another $resource service with the new parameter (:tag) and use it in your search method in your angular controller.

Another way that sounds more simple and flexible to me is to just pass the search parameters in the query method, like this:

 $scope.searchart = function() {
    Articles.query({tag:$scope.selectedTag}, function(articles) {
        $scope.articles = articles;
    });
};

and then at the server side controller, read your query parameters like this:

exports.searcharticle = function(req, res) {
    Article.find(req.query).sort('-created').populate('user', 'name username').exec(function(err, articles) {
        if (err) {
            res.render('error', {
                status: 500
            });
        } else {
            res.jsonp(articles);
        }
    });
};


来源:https://stackoverflow.com/questions/21661030/create-search-articles-feature-in-mean-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!