【问题标题】:Calling child controller's method调用子控制器的方法
【发布时间】:2014-04-29 17:29:18
【问题描述】:

我有两个这样的控制器

<div ng-controller="ParentController">
    <div ng-controller="ChildController">
    ... my grid table ..
    </div>
</div>

js代码

function ParentController($scope) {
 ...
 $scope.refreshBtnClicked = function() {
    //here I want to call refreshGrid method of ChildController
 }
}
function ChildController($scope) {
 ...
 $scope.refreshGrid = function() {
 ... its using some inner variables of Child controller...
 }
}

我怎么称呼它?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    尝试这种方式,你将不得不实现你的服务功能,但这基本上是网格的东西。

    <div ng-controller="ParentController">
        <div ng-controller="ChildController">
        ... my grid table ..
        </div>
    </div>
    
    function ParentController($scope, gridService) {
     ...
     $scope.refreshBtnClicked = gridService.refresh();
    }
    function ChildController($scope, gridService) {
     ...
     do whatever you like with your gridService methods or properties.
    }
    
    your factory or service 
    angular.module('myApp')
      .service('Gridservice', function Gridservice() {
        //data and methods here
      });
    

    您还可以在控制器之间使用广播或发射来触发事件。就像你刷新一样,你的 childcontroller 数据也会更新。

    【讨论】:

    • 正是这样,您创建了一个工厂并将所有数据和方法保存在那里,然后共享它。
    • 我希望这会奏效。会检查并让你知道......谢谢很多
    • 当然。只需确保您的数据包含在工厂以及您的方法中,因为它是一个独立的对象。
    • 好的发现这个解决方案在我的情况下是完美的stackoverflow.com/questions/19038778/…
    【解决方案2】:

    使用指令,您可以在父级中“注册”子级控制器或范围。像这样的:

    app.directive('parent', function(){
        controller: function(){
            this.children = [];
            this.addChild = function(childScope){
                this.children.push(childScope);
            }
            this.callChildFunc = function(childID){
                children[childID].someFunc();
            }
        };
    
    
    })
    
    
    app.directive('child', function(){
        require: '^parent',
        link: (scope, elem, attrs, parentCtrl) {
            parentCtrl.addChild(scope)  
            scope.someFunc = function(){};
        }
    })
    

    子调用一个函数,该函数在父级中添加对其范围的引用,以便它可以调用其函数。另一种选择是在父控制器中使用$scope 而不是this,并使用隔离作用域将addChild 函数传递给子作用域。

    【讨论】:

      【解决方案3】:

      嗯,你必须用 AngularJS 的方式来做这些事情。如果您想在控制器之间共享一种方法或想法,则应将其实现为工厂或服务。然后您可以使用 emit 或 broadcast 在控制器之间同时共享此服务。

      Can one controller call another?

      【讨论】:

      • -1 是的:那是简单的文档,我可以在网上的任何地方得到这样的描述......但我希望代码 sn-p 准确地映射到我的情况
      • 好的,太好了。那么告诉我,您的 childcontroller 是如何连接到您的 gridtable 的?您只是在控制器的网格表上显示数据吗?我们可以从这里出发。
      • 是的,childcontroller 有一个工厂方法,可以从中获取数据,并在其他内部范围变量的帮助下将其显示为网格。
      • 您可以完全将这些数据和方法抽象到单例工厂服务中。然后将其传递给函数或控制器。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      相关资源
      最近更新 更多