如何在Angularjs中点击获取绑定值键?

时间:2017-04-08 11:06:35

标签: javascript angularjs

我有一个带有绑定数据的md-select下拉列表,使用ng-repeat,当按下按钮时,我需要获取该选定值的键值(该值的json键)。

这是我的js:

 $scope.checklist= [{ "val": 1, "txt": "one" }, { "val": 2, 
"txt": "two" }, { "val": 3, "txt": "three" }, { "val": 4, 
"txt": "four" }, { "val": 5, "txt": "five" }, { "val": 6, 
"txt": "six" }, { "val": 7, "txt": "seven" }, { "val": 8, 
"txt": "eight" }, { "val": 9, "txt": "nine" }, { "val": 10, 
"txt": "ten" }, { "val": 11, "txt": "eleven" }];

  $scope.searchTerm;
  $scope.clearSearchTerm = function () {
      $scope.searchTerm = '';
  };
 $scope.getDropdwnSelectedValue = function (val) {
       alert(val);
  }

Html代码:

<div layout="row">
        <md-input-container>

            <md-select ng-model="selected.key" md-on-close="clearSearchTerm()" multiple="" style="width:300px;">
                <md-select-header>
                    <input ng-model="searchTerm" type="search" placeholder="Search for ..">
                </md-select-header>
                <md-optgroup label="list">
                    <md-option ng-value="chkLst.txt" ng-repeat="chkLst in checklist|
          filter:searchTerm" >{{chkLst.txt}}</md-option>
                </md-optgroup>
            </md-select>
        </md-input-container>
    </div>
<md-button class="md-raised md-primary" ng-click="getDropdwnSelectedValue (selected)">Get Value</md-button>

2 个答案:

答案 0 :(得分:1)

ng-repeat="chkLstin checklist | ..."中的错误应该是chkLst in checklist | ...。而且,在开发过程中,您无需进行函数调用即可查看值。只需在HTML中<pre>{{selected.key}}</pre>使用它,看看您是否获得ng-model中的值。

这是working codepen

答案 1 :(得分:0)

您的范围变量具有所选值。将范围变量初始化为$scope.selected = {},您将获得$scope.selected.key中的值,因为selected.key设置为ng-model