What's the correct way to communicate between controllers in AngularJS?

前端 未结 19 2493
猫巷女王i
猫巷女王i 2020-11-21 22:02

What\'s the correct way to communicate between controllers?

I\'m currently using a horrible fudge involving window:

function StockSubgro         


        
19条回答
  •  猫巷女王i
    2020-11-21 22:50

    Starting angular 1.5 and it's component based development focus. The recommended way for components to interact is through the use of the 'require' property and through property bindings (input/output).

    A component would require another component (for instance the root component) and get a reference to it's controller:

    angular.module('app').component('book', {
        bindings: {},
        require: {api: '^app'},
        template: 'Product page of the book: ES6 - The Essentials',
        controller: controller
    });
    

    You can then use the methods of the root component in your child component:

    $ctrl.api.addWatchedBook('ES6 - The Essentials');
    

    This is the root component controller function:

    function addWatchedBook(bookName){
    
      booksWatched.push(bookName);
    
    }
    

    Here is a complete architectual overview: Component Communications

提交回复
热议问题