【问题标题】:ngSelected not working in select elementngSelected 在选择元素中不起作用
【发布时间】:2015-05-09 12:41:08
【问题描述】:

我希望输入中的值过滤下拉列表中的值,并且对于 $index == 0 的选项,ng-selected 为真。

当过滤器采取行动时,ng-selected 中的值会更改为 true,并且元素上的 selected 属性不会更改为 selected="selected"。如果我删除模型,它会按预期工作。

<div ng-app ng-controller="AppCtrl" ng-init="sigStyles.companies = ['facebook', 'twitter', 'tumblr', 'myspace']">

    <input type="text" ng-model="socialSearch"></input>

    <select>
        <option ng-repeat="company in sigStyles.companies | filter:socialSearch" value="{{company}}" ng-selected="{{$index === 0}}">{{company}}</option>
    </select>

</div>

是否有人知道如何更改选定的属性,或者是否有人知道如何进行搜索输入以根据其输入从选择中删除选项?

链接到我的小提琴here

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    所以如果不是有点冗长,上面的答案是正确的。我不建议使用手表,因为我觉得它有点麻烦。所以基本上这就是我想出的(如果我错过了什么,请随时联系我,但请记住我正在努力提供帮助 :-) Plnkr 这个我忘了包括列表,但它可以像第二个

    JS基本上是这样的……

    angular.module('myApp', []);
    
    function MainCtrl($scope) {
        $scope.options = ['as', 'b', 'c', 'a2'];
        $scope.opt1 = 0;  
        $scope.selectedOpt = $scope.options[0];
        $scope.setOption = function() {
            if($scope.options.indexOf($scope.inFilter)  > -1){
                  $scope.selectedOpt = $scope.inFilter
            };
        }
    }
    

    设置选项只是检查文本是否存在,如果存在则设置值。

    如果您想在没有匹配项时显示一条消息,我可能会推荐更多like this

    希望这会有所帮助!

    【讨论】:

    • 谢谢你,但问题是如果我在搜索中键入数组的子字符串,setOption 中的 if 语句为 false 并且 selectedOpt 停留在已被过滤掉的 options[0] 处。所以我再次需要一个条件来说明“将 selectedOpt 设置为新过滤数组的索引 0。
    • 当然,所以我更新了jsfiddle.net/w6tt4esy/23 现在,当您键入它时,它也会重新选择第一个。只是一个其他
    【解决方案2】:

    我们可以使用搜索模型作为过滤器的参数来创建一个被过滤的新数组。该数组用于 ng-select。搜索模型中的任何更改都会被监视并用于更新过滤后的数组。

    <div ng-app="myapp">
        <div ng-controller="ctrlParent">
            <input type="text" ng-model="search" />
            <select ng-model="storedModel" ng-options="opt for opt in filteredArray | filter:search"></select>
        </div>
    </div>
    

    js:

    var app = angular.module('myapp',[]);
    app.controller('ctrlParent',function($scope,filterFilter){
        $scope.list = ["facebook","twitter","tumblr","google"];
        $scope.filteredArray = $scope.list;
        $scope.storedModel = $scope.filteredArray[0];
        $scope.$watch('search',function(newValue){
           $scope.filteredArray = filterFilter($scope.list, newValue);
           $scope.storedModel = $scope.filteredArray[0];
        });    
    });
    

    工作解决方案here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多