Javascript 防止失去焦点时ng select触发

Javascript 防止失去焦点时ng select触发,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我在Angular js中创建了一个多选框,其中包含来自数据库的值,其中一些值在满足某些条件时会被预选 fooSearch.html <select multiple ng-model="foo"> <option ng-repeat="item in fooList" value="{{item.id}}" ng-selected="fooIsSelected(item.id)"> {{item.label}} &

我在Angular js中创建了一个多选框,其中包含来自数据库的值,其中一些值在满足某些条件时会被预选

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>
<!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>

问题在于,每当触发另一个元素focus
fooIsSelected(id)
并重新选择用户可能未选择的任何项目时。无论用户在多选框失去焦点之前选择或未选择了什么选项,都会发生这种情况。为什么要这样做?在
scope.foo
上放置
$watch
并设置标志的情况下,是否有办法防止出现这种情况?

在我看来,您似乎误用了所选的
ng

ngSelected-如果表达式为truthy,则将在元素上设置特殊属性“selected”

我不认为您的代码中有任何逻辑来判断选项是被选中还是被取消选中。。它始终只计算
fooIsSelected
,而不考虑用户选择的内容。我写下了这段代码,希望对您有所帮助:

app.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;
}; 
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

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


选择多个
通常是一个笨拙的UI设备;不是每个人都意识到可以通过查看来选择多个项目。我建议用复选框代替它。也就是说,这可能就是你想要的。经过更多的测试,我更新了我的问题。只要另一个元素获得焦点,问题就会出现。当所讨论的选择框失去焦点时就不会了。向上投票,因为这似乎是一个好的、干净的解决方案。如果我能在我的应用程序中使用它,我会接受它。