我可以在Angular js

时间:2017-07-24 10:28:42

标签: javascript angularjs controller parent

我想在特定的子控制器中运行一个函数。所有子控制器中都存在相同的函数名称。我的查询是如何从特定控制器调用该函数

家长控制器:

app.controller("parentctrl",function($scope){
$scope.clickfunc = function(){
 $scope.childmethod();
}
});

子控制器:

app.controller("childctrlone",function($scope){
$scope.childmethod= function(){
 alert(1);
}
});
app.controller("childctrltwo",function($scope){
$scope.childmethod= function(){
 alert(2);
}
});

我想从childctrltwo

调用$ scope.childmethod()

1 个答案:

答案 0 :(得分:0)

您可以通过从父级广播事件并在子级控制器中侦听此事件来实现此目的。(推荐)

app.controller("parentctrl",function($scope){
$scope.clickfunc = function(){
 $scope.$broadcast("callChildMethod",{child : 1});//1 if you want to call 1st child method or 2 if you want to call second child method
}
});
app.controller("childctrlone",function($scope){
$scope.childmethod= function(){
 alert(1);
}
$scope.$on("callChildMethod",function(event,args){
if(args.child == 1) $scope.childMethod()
})
});
app.controller("childctrltwo",function($scope){
$scope.childmethod= function(){
 alert(2);
}
$scope.$on("callChildMethod",function(event,args){
if(args.child == 2) $scope.childMethod()
})
});

其他方式(但不推荐) -

使用$$ childHead或$$ childTail -

// will only work if app controller has only two childs in order
 app.controller("parentctrl",function($scope){
    $scope.clickfunc = function(){
      $scope.$$childHead.childMethod();// first child
      $scope.$$childHead.$$nextSibling.childMethod(); // second child
      $scope.$$childTail.childMethod()// second child
      $scope.$$childTail.$$previousSibling.childMethod()//first child
    }
 });

使用angular.element()

 app.controller("parentctrl",function($scope){
    $scope.clickfunc = function(){
      angular.element("#idofFirstChild").scope().childMethod();// first child
      angular.element("#idofSecondChild").scope().childMethod(); // second child
    }
 });