当焦点丢失时,防止ng-select被触发

时间:2014-10-20 14:59:40

标签: 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)被触发并重新选择可能未被用户选择的任何项目时。无论用户在多选框失去焦点之前选择或取消选择哪些选项,都会发生这种情况。它为什么这样做?有没有办法阻止这种情况,只需在$watch上放置scope.foo并设置标记?

1 个答案:

答案 0 :(得分:2)

对我来说,似乎是在滥用ng-selected来自documentation

  

ngSelected - 如果表达式是真实的,那么特殊属性&#34;选择&#34;将在元素

上设置

我并不认为您的代码中有任何逻辑可以查看是否同时选择或取消选择..它仅评估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>