Angular JS-使用功能重置下拉列表 [英] Angular JS - Resetting a dropdown with a function

查看:182
本文介绍了Angular JS-使用功能重置下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular中设置了一个侦听器,以在选择框的选项更改时触发事件.

I have a listener set up in Angular to trigger an event when a select box's option changes.

我还有一个按钮,我想将选择框重置"为空白(非选项1).

I also have a button, which I want to "reset" the selection box to blank (NOT option 1).

以下是一些代码:

HTML:

<select id="dropdown" ng-model="orderProp" >
  <option ng-repeat="cats in categories" value="{{cats}}">{{cats}}</option>
</select>
<button id="showHide" ng-click="showAll($event)" >Show all results</button>

Javascript:

Javascript:

$scope.showAll = function($event){
    $scope.orderProp ="0";
}

选择框上的侦听器功能:

Listener function on the select box:

   $scope.$watch( 'orderProp', function ( val ) {
        $scope.filteredMarkersProperty = $filter('filter')($scope.markersProperty, val);
        $scope.zoomProperty = 11;
        calcFocus();
    });

这种KINDA可以工作,虽然只是有时,但我不知道为什么,它可以工作(或不起作用),因为我认为这是错误的解决方法.我尝试使用jQuery .prop('selectedIndex',0);重置它,但是虽然这会重置索引,但它根本不会触发监听功能,因此将无法正常工作.

This KINDA works, although only sometimes, and I have no idea why it works (or doesn't) as I think it's the wrong way of going about it. I tried resetting it with jQuery .prop('selectedIndex',0);, but while this resets the index it doesn't trigger the listening function at all so this won't work.

有什么想法吗?

推荐答案

首先-看一下select指令中的ngOptions:

First - take a look at ngOptions in the select directive: http://docs.angularjs.org/api/ng.directive:select

<select ng-options="cats for cats in categories" ng-model="orderProps"></select>

<button ng-click="orderProps='0'">Show all results</button>

只要"0"不是类别之一,此选项将起作用.当orderProps的值与类别中的任何值都不匹配时,选择框将显示为空白.

This will work as long as '0' is not one of the categories. The select-box will show a blank when the value of orderProps does not match any of the values in categories.

您的$ watch函数不是选择框上的侦听器,它监视orderProps,并且orderProps可以在选择框外更改.如果您想在选择框上添加一个侦听器,则可以添加一个ng-change ="myOnChangeFn()".

Your $watch function is not a listener on the select box, it watches orderProps and orderProps can get changed outside the select box. If you want a listener on the select box you could add a ng-change="myOnChangeFn()".

添加了可正常工作的plunkr: http://plnkr.co/edit/fqWkJBYOXGaYsK9Fnedc?p=preview

Added a working plunkr: http://plnkr.co/edit/fqWkJBYOXGaYsK9Fnedc?p=preview

这篇关于Angular JS-使用功能重置下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆