ng-click - 使用属性值的函数

时间:2015-09-17 18:09:11

标签: javascript angularjs object

我在AngularJS中创建了一个计算器应用,但遇到了ng-repeatng-click的问题。

<div class="col-md-3">
  <button ng-repeat="op in operations" name="btn{{ op.name }}"
          value="{{ op.symbol }}" class="operationbutton" 
          ng-click="{{ op.function }}"> {{ op.symbol }}
  </button>
</div>

在我的app.js内,在我的控制器中,我有一个与$scope绑定的操作变量。

$scope.operations = [
    { "symbol": "+", "name": "add", "function": "add()" },
    { "symbol": "-", "name": "subtract", "function": "subtract()" },
    { "symbol": "*", "name": "multiply", "function": "multiply()" },
    { "symbol": "/", "name": "divide", "function": "divide()" }
];

我尝试从函数名称中删除引号,但事实证明JavaScript对象值必须包含字符串。

我可以做这样的事情

ng-click="{{ op.name === 'add' ? add() : op.name === 'subtract' ? subtract()
: op.name === 'multiply' ? multiply() : op.name === 'divide' ? divide() : multiply()}}"

但这似乎是一种可怕的做法。有什么方法可以改进这个,所以我可以根据操作调用一个函数吗?

3 个答案:

答案 0 :(得分:4)

最好的方法是为每个op分配实际函数,而不是函数调用的字符串表达式:

function add(){
  // whatever you do now
}

// same for other functions
function subtract(){}
function multiply(){}
function divide(){}

$scope.operations = [
    { "symbol": "+", "name": "add", "function": add },
    { "symbol": "-", "name": "subtract", "function": subtract },
    { "symbol": "*", "name": "multiply", "function": multiply },
    { "symbol": "/", "name": "divide", "function": divide }
];

ng-click成为:

<button ng-repeat="op in operations"  
        ng-click="op.function()"> 
  {{ op.symbol }}
</button>

答案 1 :(得分:1)

您可以通过这种方式重新组织代码。您可以在控制器中定义添加到$ scope对象的函数。

var add = function() {
 //code here
 }    

var subtract = function() {
 //coder her
 }     
$scope.operations= [
    { "name" : "add", "func" : add},
    { "name" : "subtract", "func" : subtract},
    ]

在html中你会这样做这样引用它们

  <div class="col-md-3">
  <button ng-repeat="op in operations" ng-click="op.func()"> {{ op.symbol }}
  </button>
  </div>

答案 2 :(得分:0)

$scope.operations = [
    { "symbol": "+", "name": "add"},
    { "symbol": "-", "name": "subtract"},
    { "symbol": "*", "name": "multiply"},
    { "symbol": "/", "name": "divide"}
];

<div class="col-md-3">
  <button ng-repeat="op in operations" name="btn{{ op.name }}"
          value="{{ op.symbol }}" class="operationbutton" 
          ng-click="op.Operationfunction(op.name)"> {{ op.symbol }}
  </button>
</div>

$scope.Operationfunction = function(operation){
switch(operation)
 case 'add':
  add();
  break;
 case 'multiply':
  multiply();
  break;
....
};