Passing ng-repeat data to another state in angular

2019-09-14 17:13发布

问题:

I am facing some problem with ui-router in angularjs. I am trying to pass data from one state to another.

Data:

$scope.MyData = [

{
  "name": "Alice",
  "age": "20",
  "email": "example@example.com"
},

{
  "name": "Bob",
  "age": "20",
  "email": "example1@example.com"
}
];

View:

  <div ng-repeat="data in MyData" >
        <div>
          <span>Name: {{data.name}}</span>
          <span>Age: {{data.age}}</span>
        </div>
   </div>

When user clicks on this div, I want to display email data for clicked contact in contact.details state view.

Controller:

 .config(function($stateProvider, $urlRouterProvider) {
      $stateProvider
        .state('contact.list', {
          url: '/contacts',
          templateUrl: 'templates/contact-list.html',
          controller: 'contactCtrl'
        })

        .state('contact.details', {
          url: '/contactdetails',
          templateUrl: 'templates/contact-details.html',
          controller: 'contactCtrl'
        })

回答1:

Your contact.details state should have params .Like this:

.state('contact.details', {
    url: '/contactdetails',
    params: {contact: null},
    templateUrl: 'templates/contact-details.html',
    controller: 'contactCtrl'
})

put the following attribute from where you want to open the above state:

<a ... ui-sref="contact.details({contact: data})" ...>...</a>

And, you should be able to navigate to that state with given information. You can access contact in contact.details's controller by injecting $stateParams and then with $stateParams.contact