How in one controller to get the value from another controller?

You have an angular app. Using ui-select.

<div class="col-md-12" ng-controller="FlatController as flat">
   <form ng-submit="flat.createFlat()">
      <ui-select ng-model="flat.flatData.typelocal" theme="bootstrap">
          <ui-select-match placeholder="Type" id="localtype">
              {{ $select.selected.type }}
          </ui-select-match>
          <ui-select-choices repeat="uitypelocal.type as uitypelocal in flat.typelocal1 track by $index | filter: $select.search">
             <div ng-bind-html="uitypelocal.type | highlight: $select.search"></div>
          </ui-select-choices>
      </ui-select>
       <button class="btn btn-danger">Send</button>
  </form>
</div>

      

In the form, I have multiple inputs and select. Now, I want to have in the selected data from another controller. How can i do this?

I have a service:

angular.module('flatService', [])
    .factory('Flat', function($http){
        var flatFactory = {};

        flatFactory.allFlats = function(){
            return $http.get('/api/flats');
        };

        flatFactory.create = function(flatData){
            return $http.post('/api/addflat', flatData);
        };

        return flatFactory;

    })
});

      

+3


source to share


3 answers


If you want to call one controller to another, there are five available methods

  • $ rootScope. $ emit () and $ rootScope. $ broadcast ()
  • If the second controller is a child, you can use the parent-child relationship.
  • Use services
  • The kind of hack is with angular.element ()
  • enter '$ controller'

1. $ rootScope. $ emit () and $ rootScope. $ broadcast ()

The controller and its scope can be destroyed, but the $ rootScope remains in the application, so we take the $ rootScope because $ rootScope is the parent of all scopes.

If you are doing parent-to-child communication and even the child wants to communicate with his siblings, you can use $ broadcast

If you are doing child-to-parent communication, no siblings are returned, you can use $ rootScope. $ emit

Html

<body ng-app="myApp">
    <div ng-controller="ParentCtrl" class="ng-scope">
      // ParentCtrl
      <div ng-controller="Sibling1" class="ng-scope">
        // Sibling first controller
      </div>
      <div ng-controller="Sibling2" class="ng-scope">
        // Sibling Second controller
        <div ng-controller="Child" class="ng-scope">
          // Child controller
        </div>
      </div>
    </div>
</body>

      

Angular code

 var app =  angular.module('myApp',[]);//We will use it throughout the example 
    app.controller('Child', function($rootScope) {
      $rootScope.$emit('childEmit', 'Child calling parent');
      $rootScope.$broadcast('siblingAndParent');
    });

app.controller('Sibling1', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside Sibling one');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

app.controller('Sibling2', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside Sibling two');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

app.controller('ParentCtrl', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside parent controller');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

      

In the above code console, $ emit 'childEmit' will not call inside child sisters and will only call inside parent where $ broadcast gets called inside siblings and parents. This is where performance comes into play. $ emit is preferred if you are using child-to-parent communication because it skips some dirty checks.

2. If the second controller is a child then you can use Child Parent

Its one of the best methods. If you want to do parental communication with the parents where the child wants to communicate with the immediate parent then he will not need any kind of $ broadcast or $ emit, but if you want to do parent-to-child communication then you need to use either the service or $ broadcast

For example HTML: -

<div ng-controller="ParentCtrl">
 <div ng-controller="ChildCtrl">
 </div>
</div>

      

Angularjs

 app.controller('ParentCtrl', function($scope) {
   $scope.value='Its parent';
      });
  app.controller('ChildCtrl', function($scope) {
   console.log($scope.value);
  });

      



Whenever you use parent-parent communication, Angularjs will look for a variable inside the child. If it is not inside, it will pick values ​​inside the parent controller.

3.Use services

AngularJS supports the concept of "Separation of Concerns" using a service architecture. Services are javascript functions and are responsible for performing specific tasks only. This makes them individually maintainable and verifiable . Services used for injection using Mackahnism Dependency Injection method for Angularjs.

Angularjs code:

app.service('communicate',function(){
  this.communicateValue='Hello';
});

app.controller('ParentCtrl',function(communicate){//Dependency Injection
  console.log(communicate.communicateValue+" Parent World");
});

app.controller('ChildCtrl',function(communicate){//Dependency Injection
  console.log(communicate.communicateValue+" Child World");
});

      

It will output Hello Child World and Hello Parent World. According to Angular's Singletons service docs, every component that depends on a service gets a reference to a single instance generated by the service factory.

4.Kind of hack - using angular.element ()

This method gets scope () from an element by the Id / unique method class.angular.element () returns the element and scope () sets the $ scope variable to another variable using the $ scope variable of one controller inside another is not good practice.

HTML: -

<div id='parent' ng-controller='ParentCtrl'>{{varParent}}
 <span ng-click='getValueFromChild()'>Click to get ValueFormChild</span>
 <div id='child' ng-controller='childCtrl'>{{varChild}}
   <span ng-click='getValueFromParent()'>Click to get ValueFormParent </span>
 </div>
</div>

      

Angularjs: -

app.controller('ParentCtrl',function($scope){
 $scope.varParent="Hello Parent";
  $scope.getValueFromChild=function(){
  var childScope=angular.element('#child').scope();
  console.log(childScope.varChild);
  }
});

app.controller('CarentCtrl',function($scope){
 $scope.varChild="Hello Child";
  $scope.getValueFromParent=function(){
  var parentScope=angular.element('#parent').scope();
  console.log(parentScope.varParent);
  }
}); 

      

The above code controllers display their own value in the Html and when you click on the text you will get the values ​​in the console accordingly. If you click on the parent controller, the browser will pass the value of the child and vice versa.

5.inject '$ controller'

You can inject the $ controller service into your parent controller (MessageCtrl) and then create / inject a child controller (DateCtrl) using:
$scope.childController = $controller('childController', { $scope: $scope.$new() });

You can now access data from your child controller by calling its methods, since this is a service.
Let me know if you run into any problems.

+5


source


The viewport is defined by its controller. However, angular allows nested view inheritance to be inherited, which means that a view nested within another view has access to the scope of the parent view. For example:

<div ng-controller="OuterCtrl">
   <div ng-controller="InnerCtrl">
      ...
   </div>
<div>

      

the inner div will have access to the InnerCtrl area as well as the OuterCtrl area, but the outer div will only have access to the OuterCtrl area.



If you need data to be shared between unrelated controllers (those that are not linked by nested views) then the data should be provided by a service that can be injected into controllers such as:

app.factory('service', function() {
   ...
   return {
     data: someData
   };
});

app.controller('ctrl1', [... function(..., service) {
    $scope.data = service.data;
}]);

app.controller('ctrl2', [... function(..., service) {
    $scope.data = service.data;
}]);

      

+2


source


use $ widecase or $ emit event like:

app.controller('ctrl1', ['$scope', '$rootScope', function($scope, $rootScope) {
    $rootScope.$on("CustomEvent", function($event, data){
      alert(data);
    })
}]);

app.controller('ctrl2', ['$scope', function($scope) {
   $scope.$emit("CustomEvent", "SecondControllerValue");
}]);

      

0


source







All Articles