javascript AngularJs 使用参数调用父控制器函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29668358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:53:03  来源:igfitidea点击:

AngularJs call parent controller function with parameter

javascriptangularjsmodel-view-controller

提问by user4773604

I have two controller's and I want to call other parent controller function with parameter when user clicks the button.

我有两个控制器,我想在用户单击按钮时使用参数调用其他父控制器函数。

Html

html

<a ng-click='test('something')'>Click</a>

Controller

控制器

controller: function($scope) {
        ..........
   $scope.test= $scope.$parent.parentTest(t);// it fails...

..........}

Parent Controller

父控制器

$scope.parentTest= function(m) {

   var my=m;

   ...Something...

}

If I run function without any parameter, it works. If I run the function with parameter it doesn't.

如果我在没有任何参数的情况下运行函数,它就可以工作。如果我使用参数运行该函数,则不会。

I want to call parent function with parameter.

我想用参数调用父函数。

回答by HankScorpio

The mistake in your code is with this line:

您的代码中的错误在于这一行:

//This assigns the RESULT of parentTest() to $scope.test
$scope.test= $scope.$parent.parentTest(t);

// Either of the 2 options below will probably work for you.

// 以下两个选项中的任何一个都可能适合您。

//This assigns the parentTest Function itself to $scope.test
$scope.test= $scope.$parent.parentTest;

//This wraps it safely in case the parentTest function isn't ready when
// this controller initializes
$scope.test= function(t){$scope.$parent.parentTest(t)}; // << Change it to this!

回答by stackg91

Check this plunkr, maybe this can help you

检查这个 plunkr,也许这可以帮助你

plunkr

access parentfunction in child controller

在子控制器中访问父函数