Mikyas TADESSE Mikyas TADESSE - 1 year ago 77
AngularJS Question

How to pass arguments to controller in angularjs?

I am currently coding a simple forum website using the mean stack. I Am at the point where I am displaying the content of a given topic. To do this I am using an ng-model so that the user enters the name of the topic and then I query my mongodb. The problem is after a refresh the user has to enter the name again to get the desire content. How can I code so that the user selects a topic and the proper content gets displayed?

Answer Source

I'll let you fill in the blanks for what you need (or you can ask further questions), but here is some basic code from the Angular side of things to hit an endpoint and retrieve some data and display it in a view.

You'll need UI Router as described in Gustavo's answer.

App - the config in here will allow you to refresh the page and still be able to keep the topic that you want.

angular.module('app', ['ui.router'])
  .config(function($stateProvider) {
    $stateProvider.state('topics', {
      url: '/topics/:topic',
      templateUrl: 'path_to_template.html',
      controller: 'myController'

Service - this will talk to your API which will grab the data for you.

  .service('myService', function($http) {
    this.getInfo = function(topic) {
      return $http.get('path_to_api', { params: { topic: topic } });

Controller - this will be what binds your template to your scope which will allow you to display results.

  .controller('myController', function($scope, $stateParams, myService) {

    function activate() {
        .then(function(result) {
          $scope.topicInfo = result;

Hope this helps - happy to answer any other questions you may have.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download