user3501278
user3501278

Reputation: 267

unable to pass data between the views in angularjs through routing

In my angularjs app, I am trying to pass the data from one cshtml view to another view through routing but in details.cshtml, I don't see the data coming into it though I can see the change in URL

Index.cshtml (View1)

  <a href="/#/Details/{{ cid }}" ng-click="SendToCartPage(cartprd)">{{addprodtocart}} </a>

Controller.js

app.controller('CartController', function ($scope) {
$scope.SendToCartPage = function(cartprd)
{
    var len = cartprd.length - 1;
    $scope.cid = cartprd[len];
}

});

Details.cshtml ( I don't see the data coming into the span below)

<div ng-controller="CartController">
    <span ng-model="cid">{{cid}}</span>
</div>

Myrouting

var app = angular.module("productmodule", ["ngRoute"]);
app.config(['$routeProvider',
  function ($routeProvider) {
   $routeProvider.

               when('/Details/:cid', {
                   templateUrl: '/Product/Details',
                   controller: 'CartController'
               });
  }]);

I created a plunker for this. I am unable to send the data from page1 to page2 http://plnkr.co/edit/micM7vlslznEIZXP293Y?p=preview

Upvotes: 1

Views: 352

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

Your problem is your controller is instantiated again while clicking on href and the scope is getting recreated & $scope.cid is set to undefined.

You could achieve the same by using $routeParams which will give the access to what url contains

In your case it would be $routeParams.cid

Code

app.controller('CartController', function ($scope, $routeParams) {
  $scope.SendToCartPage = function(cartprd)
  {
    var len = cartprd.length - 1;
    //$scope.cid = cartprd[len];
  }
  $scope.cid = $routeParams.cid;
});

Update

You should use $routeParams service to get data from url

Code

var app = angular.module('plunker', ['ngRoute']);
app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
    when('/Details/:cid', {
      templateUrl: 'page2.html',
      controller: 'CartController'
    }).when('/', {
      templateUrl: 'page1.html',
      controller: 'CartController'
    });
  }
]);
app.controller('CartController', function($scope, $routeParams) {
  $scope.myvar = $routeParams.cid; //this will asign value if `$routeParams` has value
  console.log($scope.myvar);
  $scope.Add = function(c) {
    $scope.myvar = c;
  }
});

Working Plunkr

Upvotes: 1

Related Questions