Serhiy Serhiy - 2 months ago 10
AngularJS Question

how to pass data into controller opened via $state.go(controller.state)?

I have array of objects.When I click on name it should open md-content page with configuration of the folder. Situation is next: when I click on name -it opens conf. page with FolderConfigController, but I want to send folder object into the FolderConfigController to work with it.

folders = [{name: name1, id:id1},{name: name2, id:id2},{name: name2, id:id2}]


listed in lefsidenav:

<div ng-repeat="folder in folders" ng-click="vm.openConfigPage()">{{folder.name}}


in folderController:

vm.openConfigPage = openConfigPage;
function openConfigPage() {
$state.go('triangular.config');
}


FolderConfigController.config:

(function() {
'use strict';

angular
.module('app.components.work')
.config(moduleConfig);

/* @ngInject */
function moduleConfig($stateProvider) {

$stateProvider
.state('triangular.config', {
url: '/work/folder/config',
templateUrl: 'app/components/work/folder-config/folder-config.tmpl.html',

controller: 'FolderConfigController',
controllerAs: 'vm',
});

}
})();


is it possible to make something like:

function openConfigPage(folder) {
$state.go('triangular.config');
FolderConfigController.folderObject = folder;
}


how it works in correct way?

Answer

You can use state params like this:

function moduleConfig($stateProvider) {

    $stateProvider
    .state('triangular.config/:id/:name', {
        url: '/work/folder/config',
        templateUrl: 'app/components/work/folder-config/folder-config.tmpl.html',

        controller: 'FolderConfigController',
        controllerAs: 'vm',
    });

}
})();

and then when you transition to that state you can set the params

function openConfigPage(folder) {
    $state.go('triangular.config', {"name": folder.name, "id": folder.id});
}

and the inject $stateParams into the FolderConfigController controller to gain access to the name and id parameters

.controller('FolderConfigController ', function($scope, $stateParams){

   console.log($stateParams):

});
Comments