Angularjs passing parameter to a page from ng-click

42,284

First of all you need to tell your destination controllers (the page you are referring to) to expect and accept a parameter when we navigate to that page:

$routeProvider.when('/api/renameShow/:showName?', { 
  controller: 'renameShowCtrl', 
  templateUrl:     '/templates/renameShow.html' 
})

The question mark after the parameter denotes that it's an optional parameter. You can achieve the same with anchor tags:

<a href="#/view2/mike">Go to view 2</a>

If you insist on using buttons, write a custom function hooking onto the ng-click of the button, and then pass whatever parameter you want like this from your current controller:

<button ng-click="customNavigate('Mike')">Rename Show</button>

And in the controller:

    $scope.customNavigate=function(msg){
       $location.path("/view2"+msg)
    }

and then in the destination controller:

app.controller("renameShowCtrl",function($scope,$routeParams){
   $scope.showName=$routeParams.showName
});
Share:
42,284
J. Davidson
Author by

J. Davidson

Updated on July 30, 2020

Comments

  • J. Davidson
    J. Davidson almost 4 years

    I have following three buttons on top of my page with input box underneath it.

    <div>
      <form>
              <div>
                  Enter Show Name<input type="text" ng-model="showName" />
              </div>
          </form>
    </div>
    <div>
    <button ng-click="href="/api/renameShow"">Rename Show</button>
    <button ng-click="href="/api/updateShow"">Update  Show</button>
    <button ng-click="href="/api/checkShow"">Check   Show</button>
    </div>
    

    My module code with routes is

        var showApp = angular.module("showApp", ["ngRoute", "ngResource", "ui"]).
        config(function ($routeProvider, $locationProvider) {
            $routeProvider.
                when('/',
                {
                    controller: '',
                    templateUrl: 'main.html'
                }).
                when('/api/renameShow', { controller: 'renameShowCtrl', templateUrl:     '/templates/renameShow.html' }).
                when('/api/updateShow', { controller: 'updateShowCtrl', templateUrl:     '/templates/updateShow.html' }).
    when('/api/checkShow', { controller: 'checkShowCtrl', templateUrl: '/templates/checkShow.html' });
    

    Basically what I am trying to do is that when one of the buttons is clicked the ng-click calls the corrosponding page passing the parameter "showName" with it. Please let me know how to fix it. Thanks

  • Sagi
    Sagi about 7 years
    I Think you missed a slash in the path : $scope.customNavigate=function(msg){ $location.path("/view2/"+msg) }
  • Sagi
    Sagi about 7 years
    Otherwise great answer.