如何让子控制器访问父控制器中的功能

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 似乎是一个函数本身,returns 您期望的对象。因此,$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 是一个函数。这样的话,在child中,首先需要先调用searchRibbon函数,再调用hide函数

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

或者,您可以将 $scope.searchRibbon 声明为 object,而不是函数(更容易并避免范围问题)。

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();
  });