如何在按钮点击时多次调用一个函数?

时间:2015-04-16 09:42:00

标签: javascript angularjs angularjs-scope

for (var i = 0; i < malls.length; i++) {
  mall = malls[i];
  codeAddress(mall);
}

$scope.codeAddress = function(mall){}

HTML

<ion-nav-buttons side="primary">
  <button class="button" ng-click="codeAddress()">
    Find Me
  </button>
</ion-nav-buttons>

<div id="map" data-tap-disabled="true"></div>

嗨,当我在循环中调用一个函数时,我收到此消息: ReferenceError:未定义codeAddress

3 个答案:

答案 0 :(得分:3)

您忘记了$scope

$scope.codeAddress = function(mall){} // add this above the loop

for (var i = 0; i < malls.length; i++) {
     mall = malls[i];
     $scope.codeAddress(mall);
}

JSFIDDLE示例。

答案 1 :(得分:0)

您可以使用setInterval循环带有时间参数的函数

var counter = 0;
 var i = setInterval(function(){
// do your thing
Somefunctionyouwanttoloop()
counter++;
if(counter === 10) {
    clearInterval(i);
}
}, 200);

答案 2 :(得分:0)

如果要在按钮单击时多次调用该函数,可以创建一个包含循环的包装函数:

baseFun = function(mall){...}

$scope.wrapperFun = function(arg){
  for (var i = 0; i < arg.length; i++) {
   baseFun(arg[i]); //in example codeAddress()
  }
}

然后html代码将如下所示:

<button class="button" ng-click="wrapperFun(mails)">

另外,正如您所看到的,您仍然需要将mails参数传递给该函数。请查看工作示例:jsfiddle