In Angularjs, each controller has a corresponding scope, and the scope sometimes requires communication. For example, there is a controller nesting as follows:
<BodyNg-controller= "Appctrl"> <TableNg-controller= "Productctrl"> ... <TRng-repeat= "Product in Products"> <TD>{{$index + 1}}</TD> <TD>{{Product.name}}</TD> <TD>{{Product.price | currency}}</TD> <TD><ButtonNg-click= "AddToCart (product)">Add to Cart</Button></TD> </TR> </Table> <DivNg-controller= "Cartctrl"> ... <TRng-repeat= "Product in cart"> <TD>{{$index +1}}</TD> <TD>{{Product.name}}</TD> <TD>{{Product.price | currency}}</TD> <TD><ButtonNg-click= "Removefromcart (product)">Remove</Button></TD> </TR> </Div></Body>
The corresponding controller section is roughly:
function ($scope) { = "Product Manager";}) Myapp.controller (function($scope) { = [ {name:"", Price:50}, ... ]; function () { }}); Myapp.controller (function($scope) { = []; function (product) { }});
Above, the relationship between scopes is as follows:
$rootScope
... $scope of Appctrl
... $scope of Productctrl
... $scope of Cartctrl
The question is, Productctrl need to put product in the cart, the cart needs to get to product, how to communicate between the two ?
→ When performing addtocart actions in Productctrl, let $rootscope send a broadcast informing all child scopes
function ($scope, $rootScope) { = [ {name:"", Price:50}, ... ]; function (product) { // let $rootscope send a broadcast, all child scopes know $rootScope. $broadcast (" Addproduct ", product);} )
Visible, $rootScope broadcast events through the $broadcast method, an argument is the event name, and an argument is the object to be passed.
→ in Cartctrl, you need to listen for events from $rootscope, and also to inform the higher-level scope of the event that removed the product
function ($scope) { = []; // child scope to listen for Rootscope events $scope. $on ("Addproduct", add); function Add (evt, product) { $scope. Cart.push (product); } function The event in the (product) { // sub-scope tells the higher scope $scope. $emit ("Removeproduct" , product);} )
It is visible that the $on method listens to the Addproduct event from $rootscope in the child $scope and executes a callback function, and if an event is executed in a child $scope to tell a higher level scope, here is the Removefromcart event, You need to pass the $emit method, where the first argument is also the event name, and the second argument is the passing object.
→ in Appctrl for removeproduct events from Cartctrl
function ($scope) { $scope. $on (function(evt, data) { + "removed") })
It is also visible that the $on method listens for events emitted by emit in the child $scope.
ANGULARJS Inter-scope communication demo