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

时间:2015-07-27 14:33:09

标签: javascript angularjs angularjs-scope ng-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

由于

2 个答案:

答案 0 :(得分:3)

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
    }
}

答案 1 :(得分:1)

我注意到$ 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();
  });