How do I pass a parameter to another Scope with Angularjs?

Asked

Viewed 7,111 times

13

I have a screen that contains a list of information, when clicking on some item I can get his number, for example: Item 5 of array.

The problem is that on another screen I need to display the information of the item that was clicked, and I don’t know how to pass this reference to another scope ($scope).

Can someone please help me?

  • There are several ways to do this, which are more or less appropriate according to their architecture. This other screen is encapsulated in a directive? Or is a view different? Or even accessed from a completely different page? Please provide minimal code to help you better.

2 answers

9

The recommended way to share values between Controllers is using Services. Example to follow:

angular.module('minhaApp', [])
    .service('PropriedadesCompartilhadas', function () {
        var ItemSelecionado = '';

        return {
            getItem: function () {
                return ItemSelecionado;
            },
            setItem: function(value) {
                ItemSelecionado = value;
            }
        };
    });

In your controller, you can consume this service via injection:

function Ctrl($scope, PropriedadesCompartilhadas) {
    //Obtém valor
    $scope.ValorSelecionado = PropriedadesCompartilhadas.getItem();

    //Seta valor
    PropriedadesCompartilhadas.setItem(1);
}

Original reference: 'How can I pass variables between controllers?', ONLY ORIGINAL.

3

You can configure your route as follows:

 $stateProvider.state('detalhes', {
            url: '/detalhes/{idItem}',
            templateUrl: 'detalhes.html',
            controller: 'DetalhesCtrl'
        });

To pass the item id you put in the link:

<a ui-sref="detalhes({idItem: idDoItem})">Nome do item</a>

To get the id of the item sent to the controller would be:

app.controller('DetalhesCtrl', function ($scope, $stateParams) {

    var idItem = $stateParams.idItem; 

});

Then you can use this ID to get the item information. From what I understand of the question I believe it solves

Browser other questions tagged

You are not signed in. Login or sign up in order to post.