在angularjs中给ng-click函数传递参数

passing parameters to ng-click's function in angularjs

本文关键字:参数 函数 ng-click angularjs 中给      更新时间:2023-09-26

在ng-click中如何传递作用域参数的引用你可以选择我想要的

http://plnkr.co/edit/Em7LiNStICjZA23pSph3?p =预览

通常,您不需要动态地执行此操作,因为您将在inputs上具有特定的$scope属性等。

这是一个更新的活塞。

HTML:

<div class="test" ng-controller="Ctrl">
   <button ng-click="update(1, 'text1');">update text 1</button>
   <button ng-click="update(2, 'text2');">update text 2</button>
    {{text1}} , {{text2}}
<div>

JS:

function Ctrl($scope) {
  $scope.update = function(parameter1, textVar){
      if (parameter1 === 1) {$scope[textVar] = "1"}
      if (parameter1 === 2) {$scope[textVar] = "2"}
  };
}

你可以,但我认为你把一些东西混在一起了。在您的代码中,您将textVar变量设置为1或2。但是,这个变量永远不会被使用。

你必须将元素绑定到作用域上的一个变量,然后在你的update函数中更新相关的作用域变量,例如:

$scope.update = function(button, text) {
  if(button == 1) {
    $scope.text1 = text;
  } else if(button == 2) {
    $scope.text2 = text;
  }
}

和你的HTML:

<button ng-click="update(1,'Text for text1');">update text 1</button>
<button ng-click="update(2, 'Text for text2');">update text 2</button>
<span ng-bind="text1"></span>, <span ng-bind="text2"></span>