调用路由中的父控制器函数

Call parent controller function in route

本文关键字:控制器 函数 路由 调用      更新时间:2023-09-26

我正在使用ngRoute,我需要调用路由控制器中的父控制器函数。(我不使用$scope)index.html的一部分:

<div class="col-lg-12" ng-controller="IndexController as index">
    <div ng-view>
    </div>
</div>

和父控制器:

(function(){
    'use strict';
    angular
        .module('project')
        .controller('IndexController', IndexController);
    function IndexController() {
        var vm = this;
        vm.hello = function() {
            console.log("Hello from parent controller");
        }
    }
})();

如何在路由控制器中调用hello()?

首先需要在模块声明中添加一个空的依赖数组。。

.module('project', [])

然后你需要调用你的函数。。像这样使用按钮。

<div class="col-lg-12" ng-controller="IndexController as index">
  <div ng-view>
    <button ng-click="index.hello()"></button>
  </div>
</div>