簡體   English   中英

如何讓子控制器訪問父控制器中的功能

[英]How to get Child Controller to access function in Parent Controller

我有一個簡單的父和子控制器設置,我試圖讓我的子控制器在父控制器中調用一個函數:

HTML:

<div ng-controller="Parent>

    <p ng-hide="ribbonHide">{{ribbonMessage}}</p>

    <div ng-controller="Child">


    </div>

</div>

Parent.js:

app.controller('Parent', function($scope, $timeout) {
    $scope.searchRibbon = function() {
        return {
            default : function() {
                $scope.ribbonMessage = 'Welcome';
                $scope.ribbonHide = false;
            },
            clearMessage: function() {
                $scope.ribbonMessage = '';
            },
            hide: function() {
                $scope.ribbonHide = true;
            },
            autoRemove: function() {
                $timeout(function() {
                    $scope.searchRibbon.hide();
                    $timeout(function() {
                        $scope.searchRibbon.clearMessage();
                    }, 500);
                }, 5000);
            }
        }
    }
});

Child.js

app.controller('Child', function($scope, $timeout) {
    $scope.$parent.searchRibbon.autoRemove();
});

有了上述,我得到了錯誤:

TypeError: $scope.$parent.searchRibbon.autoRemove is not a function

謝謝

searchRibbon似乎是一個函數本身,它將返回您期望的Object。 這樣, $scope.$parent.searchRibbon().autoRemove()應該可以工作。

但這似乎很奇怪。 您確定不希望searchRibbon成為標准對象嗎?

$scope.searchRibbon = {
    default : function() {
        $scope.ribbonMessage = 'Welcome';
        $scope.ribbonHide = false;
    }, // ... the other ribbon properties go here
}

如果需要函數提供的作用域,則可能需要遵循以下方法:

$scope.searchRibbon = getSearchRibbon();

function getSearchRibbon() { // This should probably be in a Service
    return {
        default : function() {
            $scope.ribbonMessage = 'Welcome';
            $scope.ribbonHide = false;
        }, // ... the other ribbon properties go here
    }
}

我注意到$ scope.searchRibbon是一個函數。 在這種情況下,對於孩子,您首先需要先調用searchRibbon函數,然后再調用hide函數

$scope.$parent.searchRibbon().hide();

或者,您也可以將$ scope.searchRibbon聲明為一個對象,而不是一個函數(更加容易,避免出現范圍問題)。

 angular.module("app", []) .controller('Parent', function($scope, $timeout) { $scope.searchRibbon = { default: function() { $scope.ribbonMessage = 'Welcome'; $scope.ribbonHide = false; }, clearMessage: function() { $scope.ribbonMessage = ''; }, hide: function() { $scope.ribbonHide = true; }, autoRemove: function() { $timeout(function() { $scope.searchRibbon.hide(); $timeout(function() { $scope.searchRibbon.clearMessage(); }, 500); }, 5000); } } }) .controller('Child', function($scope, $timeout) { $scope.$parent.searchRibbon.hide(); }); 

暫無
暫無

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

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