2014-10-20 25 views
0

我有一个在Angular js中使用数据库中的值创建的多选框,其中一些预选符合特定条件。防止ng-select在焦点丢失时发射

fooSearch.html

<select multiple ng-model="foo"> 
    <option ng-repeat="item in fooList" 
      value="{{item.id}}" 
      ng-selected="fooIsSelected(item.id)"> 
    {{item.label}} 
    </option> 
</select> 

fooSearch-dctv.js

scope.foo = []; 
scope.fooIsSelected = function(id){ 
var isBar = PermissionsFxty.hasPermission('A_PERM') && (id == "15" || id == "16" || id == "17"); 
var isBaz = PermissionsFxty.hasPermission('B_PERM') && (id == "1" || id == "3"); 

if((isBar || isBaz) && scope.foo.indexOf(id) == -1){scope.foo[scope.foo.length] = id;} 

return isBar || isBaz; 
}; 

的问题是,每当另一个元素焦点fooIsSelected(id)被解雇,重新选择可能是未选择任何项目由用户。无论用户在多选框失去焦点之前选择或取消选择什么选项,都会发生这种情况。它为什么这样做?在scope.foo上设置$watch并设置标志,有没有办法预防这种情况?

+0

'选择multiple'是通常是一个尴尬的UI设备;不是每个人都意识到可以通过查看来选择多个项目。我会建议用复选框替换它。这就是说,[ngModelOptions](https://docs.angularjs.org/api/ng/directive/ngModelOptions)可能就是你要找的。 – Blazemonger 2014-10-20 15:15:25

+0

经过一些更多的测试后,我更新了我的问题。每当其他元素获得焦点时就会出现问题。不是当有问题的选择框失去焦点时。 – 2014-10-20 16:13:46

回答

2

在我看来,像你这样滥用ng-selected,从documentation

ngSelected - 如果表达式为truthy, “选择”,那么特殊的属性将在元素上设置

而且我认为代码中没有任何逻辑可以查看是否同时选择了选项或取消选择。它只会始终评估fooIsSelected,而不考虑用户选择或不选择的内容。我写下了这段代码,希望你会发现它有用,here is also a working plunker

app.js

var values = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ]; 

function MyCntrl($scope) { 
    $scope.prop = { 
    "type": "select", 
    "name": "id", 
    "selectedValues": someFilterFunction(values), 
    "values": values 
    }; 
} 

function someFilterFunction(array) { 
    // Write any filter you desire here. 
    return array.filter(function(x) { return x == 3 || x == 5 || x == 7 }); 
} 

的index.html

<!doctype html> 
<html ng-app> 
    <head> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script> 
    <script src="app.js"></script> 
    </head> 
    <body> 
    <div ng-controller="MyCntrl"> 
     <select style="height: 200px" multiple ng-model="prop.selectedValues" ng-options="v for v in prop.values"> 
     </select> 
    </div> 
    </body> 
</html> 
+0

因为这看起来像一个很好的,干净的解决方案。如果我可以在我的应用程序中工作,我会接受它。 – 2014-10-20 16:26:15