javascript - 防止 ng-select 在焦点丢失时触发

标签 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}}
  </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 并设置标志?

最佳答案

在我看来,您似乎滥用了 ng-selected,来自 documentation :

ngSelected - If the expression is truthy, then special attribute "selected" will be set on the element

而且我认为您的代码中没有任何逻辑可以同时查看选项是否被选择或取消选择。它始终只评估 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>

关于javascript - 防止 ng-select 在焦点丢失时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26468770/

相关文章:

javascript - Ember 应用程序套件当我运行 grunt dist 时,如何从包含的 js 库列表中排除 jquery

javascript - 如何使叠加效果与图像响应

javascript - 将 Angular 更新 <tfoot> 内的一个 `ng-model`

angularjs - 让嵌套 View 与 AngularJS 和 ui-router 中的多个模块一起使用

javascript - 限制 AngularJS 中的 $scope

angularjs - 如何将 Controller 动态加载到指令

javascript - Javascript和 knockout

javascript - 使用 Angular $filter 搜索和过滤深层 json 值

javascript - 从链接修改指令模板内的 ng-show

javascript - jquery resize with click 函数在宽度改变时执行点击处理程序