Items of different controllers into one


#1

Hello people. A query.
Is there a way to show items of two lists of two different controller in one single controller for example? Thanks! :smiley:

    .controller('Controlador1Ctrl', function($scope) {
  $scope.data = {};
  $scope.items = [
    { text: 'Text1', num:'12345'},
    { text: 'Text2', num:'67890'},
  ];
  $scope.clearSearch = function() {
    $scope.data.searchQuery = '';
  };
})
.controller('Controlador2Ctrl', function($scope) {
  $scope.data = {};
  $scope.items = [
    { text: 'Text3', num:'ABCD'},
    { text: 'Text4', num:'EFGH'},
  ];
  $scope.clearSearch = function() {
    $scope.data.searchQuery = '';
  };
})
.controller('ControladorFullCtrl', function($scope) {
  $scope.data = {};
  $scope.items = [
  //Items of Controlador1Ctrl and Controlador2Ctrl
    { text: 'Text1', num:'12345'},
    { text: 'Text2', num:'67890'},
    { text: 'Text3', num:'ABCD'},
    { text: 'Text4', num:'EFGH'},
  ];
  $scope.clearSearch = function() {
    $scope.data.searchQuery = '';
  };
})

#2

You can share them through AngularJS service or factory. Google them.


#3

Hello again! I found the solution I share, excuse my bad expression. Greetings! :sweat_smile:

   var app = angular.module(....);

app.controller('FirstCtrl ', function($scope) {
  $scope.items = [{id:1, desc:'desc1'},{id:2, desc:'desc2'}...];
});

app.controller('SecondCtrl', function($scope, $controller) {
  $controller('FirstCtrl', {$scope: $scope}); // $scope.items now available

});

#4

@frandearma While that may work, I recommend you look into using services or factories as suggested by @Gajotres.

Reusable functions are always best placed in a factory or service that you can dependency inject into any controllers that need them.

Services and factories are extremely common AngularJS terms so you’ll find plenty of info online.

Good luck.


#5

Hi, If you’re right, if I solved the problem well, but is not recommended. Therefore, I am choosing the solution :factory:
Thank you!
A greeting. :grinning: