Angular.js - 将具有数据绑定功能的按钮中的选定选项更改为函数参数

问题描述:

我想用按钮更改选定选项。如果我没有在参数中使用数据绑定,代码将按预期工作:Angular.js - 将具有数据绑定功能的按钮中的选定选项更改为函数参数

ng-click="changeOptions('cat');" 

如果我对参数使用数据绑定,它将不再起作用。这是不允许的?

ng-click="changeOptions('{{animals.type}}');" 

下面是HTML:

<div ng-app="quickApp" ng-controller="quickController"> 
    <select ng-model="animalList" ng-options="animals.type as animals.type for animals in animals"></select> 
    <button ng-repeat="animals in animals" ng-click="changeOptions('{{animals.type}}');">{{animals.type}}</button> 
</div> 

这里是JS:

angular 
    .module('quickApp', []) 

    .controller('quickController', ['$scope', function($scope) { 

     $scope.changeOptions = function(id){ 
       $scope.animalList = id; 
      }; 

     $scope.animals = [ 
       {'type':'cat'}, 
       {'type':'dog'}, 
       {'type':'bear'} 
     ]; 
    }]); 

你真的不需要这些大括号内。

ng-click="changeOptions(animals.type);" 

应工作

顺便说一句,你为什么不改变animals in animalsanimal in animals?两个animals似乎不明确。在这种情况下,您必须使用:

<button ng-repeat="animal in animals" ng-click="changeOptions('{{animal.type}}');">{{animal.type}}</button> 
+0

谢谢,您的建议帮助我达到了现在正确运行的程度。 最初令人困惑的是,在查看DOM时,都使用“字符串”和“{数据绑定}”作为参数呈现完全相同,但获得了不同的结果。 – sjmartin