Javascript 如何使用 angularjs 在单个 ng-init 指令中调用多个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28448149/
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-08-23 01:48:07  来源:igfitidea点击:

how to call multi function in single ng-init directice using angularjs

javascriptangularjs

提问by Udaya Ravi

I just try to call two function in single ng-init of angularjs.but it through error to me. My code:

我只是尝试在 angularjs 的单个 ng-init 中调用两个函数。但它通过错误给我。 我的代码:

ng-init="function1();function2();"

I don't know how to call those function correctly.anyone can give me some ideas to do it.
Thanls advance..

我不知道如何正确调用这些函数。任何人都可以给我一些想法。
谢谢提前..

回答by Rajeshwar

Check out the below link, and have a look at the console.

查看以下链接,并查看控制台。

http://plnkr.co/edit/60Ry6hwiunAF12PZclNW?p=preview

http://plnkr.co/edit/60Ry6hwiunAF12PZclNW?p=preview

HTML

HTML

<div ng-init='one(); two();'></div>

JS

JS

$scope.one = function(){
  console.log('one')
};

$scope.two = function(){
  console.log('two')
};

Hope this is what you are expecting

希望这是你所期待的

回答by Sandeeproop

You can create one main function like "init" and call other functions inside that function.

您可以创建一个像“init”这样的主函数,并在该函数内调用其他函数。

ng-init="init()"

from your controller

从您的控制器

function init() {
  function1();
  function2();
}

回答by New Dev

First of all, this should work, and probably the reason it doesn't is because you don't have these functions in the scope. Do you have an ng-controlleron this or ancestor element?

首先,这应该有效,可能它无效的原因是因为您在范围内没有这些功能。你有ng-controller这个或祖先元素吗?

If you do, make sure that these functions are defined on the scope:

如果这样做,请确保在范围内定义了这些函数:

.controller("MainCtrl", function($scope){
  $scope.function1 = function(){...};
  $scope.function2 = function(){...};
});

Second, you should not be using ng-initto call functions at all.

其次,您根本不应该使用ng-init来调用函数。

<div ng-controller="MainCtrl">
</div>

Instead, call these functions in the controller:

相反,在控制器中调用这些函数:

.controller("MainCtrl", function($scope){
  function1(); 
  function2();

  function function1(){...};
  function function2(){...};
});

From Angular documentation on ngInit:

来自Angular 文档ngInit

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

ngInit 唯一合适的用途是为 ngRepeat 的特殊属性设置别名,如下面的演示所示。除了这种情况,您应该使用控制器而不是 ngInit 来初始化范围上的值。