为什么ng-selected调用函数n-Times

时间:2016-01-19 16:20:33

标签: javascript angularjs

我尝试通过点击某个项目从选择框中调用一个函数。

HTML TAG

<div>
    <div class="col-sm-6">
    <h3><small>Organiser</small></h3>
    <input type="text" id="#tournament-organiser-name" ng-model="organiserName" class="form-control" name="organisert-name" ng-keyup="findOrganiser(organiserName)" />

    <div class="form-group btn-toolbar-bottom" ng-hide="searchResultshow" ng-model="searchResultshow">
        <select class="form-control" size="3"  name="singleSelect" height="40px" id="singleSelect" ng-model="organiserLikeList" >
          <option ng-repeat="option in organiserLikeList" ng-value="{{option.id}}" ng-selected="selectOrganiser(option)">{{option.name}}</option>
        </select>
    </div>

</div>

JS

$scope.selectOrganiser = function(x){
  console.log(x);
}

我试图改变指令。

参数应该是organsierLikeList中的字段。但它不起作用。

ng-click : 该功能不会调用。

ng-selected :该函数被调用n次(每次看两次)

我觉得很奇怪:

当我在文本字段中输入一个字母时,会调用该函数,但是ng-selected指令位于select-Tag中的选项-Tag。

enter image description here

2 个答案:

答案 0 :(得分:1)

您无法将点击事件绑定到各个选项元素。而是订阅整个选择框的onchange事件:

<div class="form-group btn-toolbar-bottom" ng-hide="searchResultshow">
    <select class="form-control" size="3" name="singleSelect" height="40px" id="singleSelect" 
            ng-options="option.id as option.name for option in organiserLikeList"
            ng-change="selectOrganiser()"
            ng-model="organiserSelected">
    </select>
</div>

另外,请使用ngOptions而不是ngRepeat。

答案 1 :(得分:1)

模板

<select class="form-control" size="3"  name="singleSelect" height="40px" id="singleSelect" ng-model="selectOption" >
    <option ng-repeat="option in organiserLikeList" value="{{option}}">{{option.name}}</option>
</select>

控制器

$scope.$watch("selectOption", function(newval, oldval){
    var newval_ = JSON.parse(newval);
    alert(newval_.id);
});

请参阅此链接https://plnkr.co/edit/SPiv8EzbWdvKsGgda5es?p=preview