簡體   English   中英

觀看父控制器功能

[英]Watch parent controller function

我的項目的一部分與B組分 ng-repeat ,里面成分A。
兩個組件都有不同的控制器(controller as)。
在控制器組件A中 ,創建的函數如下:

this.functionName = function(){};

發生事件ng-click時被稱為。

問題的實質:就像在組件B的控制器中一樣,每次調用此函數(控制器A)時都要執行一些動作? 我想我可以以某種方式使用$watch ,但是我想不使用$scope.$parent.$parent.$watch;

作為使用angular的事件系統的替代方法,您可以使用服務在組件之間共享狀態。

這是一個示例(為簡化示例,我在這里忽略了最佳實踐)

app.service('myService', function(){
    var service = this;
    service.items = [];

    service.addItem = function(newItem){
        service.items.push(newItem);
    }
});

app.component('cmpA', {
    template: [
        '<ul>',
            '<li ng-repeat="item in $ctrl.items track by $index">{{item}}</li>',
        '</ul>'
    ].join(''),
    controller: function(myService){
        this.items = myService.items;
        console.log(this.items);
    }
});


app.component('cmpB', {
    template: [
        '<div>',
            '<input ng-model="$ctrl.newItem" /><button type="button" ng-click="$ctrl.save()">Save</button>',
        '</div>'
    ].join(''),
    controller: function(myService){
        this.newItem = '';
        this.save = function(){
            myService.addItem(this.newItem);
            this.newItem = '';
        }
    }
});

您可以在此插件中看到它的實際效果。

希望這是您需要的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM