【问题标题】:Angular dynamic select values角度动态选择值
【发布时间】:2014-08-25 10:27:57
【问题描述】:

我在选择中有一些动态生成的values

<select ng-model="selectedValue" ng-options="o.id as o.name for o in values"></select>

我有 selectedValue 保存选定的值。当selectedValue 不再出现在values 中时,我希望它更新为nullundefined

我可以清除$scope.$watch(values)中的selectedValue,但有更好的解决方案吗?

基本上this plunker 的这种情况是我想避免的:

我希望它是“选定的值:null”或类似的东西。

【问题讨论】:

    标签: javascript angularjs angularjs-ng-model


    【解决方案1】:

    您可以创建一个指令,使选择以您想要的方式运行。然后 HTML 将更改为:

    <select clearable ng-model="selectedValue" ng-options="o.id as o.name for o in values"></select>
    

    该指令的 JS 将是:

    app.directive('clearable', ['$parse',function($parse){
      return {
        restrict : 'A',
        scope : {
          'ngModel' : '=',
          'ngOptions' : '@'
        },
        require: ['select','?ngModel'],
        link : function(scope, elem, attr,ctrl){
    
          // Regex copied from the Angular Source
          var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
          var match = scope.ngOptions.match(NG_OPTIONS_REGEXP);
    
          var valuesFn = $parse(match[7]),    //Options list
              key = match[1].split('.')[1];   //Property in options list
    
          scope.$watch(
            function(){
              // Watch for when the options list changes
              return valuesFn(scope.$parent);
            }, 
            function(newList){
              var isFound, i,
                  currentModelVal = scope.ngModel;
    
              // Iterate through the new list to see if the current value is present
              for(i=0;i<newList.length;i++){
                if (newList[i][key] === currentModelVal){
                  isFound = true;
                  break;
                }
              }
    
              // If not found, reset the ng-model value to null
              if (!isFound){
                ctrl[1].$setViewValue(null);
              }
            }
          );
    
        }
      }  
    }]);
    

    http://plnkr.co/edit/yAk9YSoMf88rtTqLXTiI?p=preview查看Plunker

    【讨论】:

      【解决方案2】:

      您可以使用具有空值的选项,当没有选择任何项目时,模型将设置为空

      检查一下

      <option value="">--select--</option>    
      

      http://plnkr.co/edit/66KN7ae0q2v3IUnw47lx?p=preview

      【讨论】:

      • 当 selectedValue 不在值中时,变量 $scope.selectedValue 应该被清除/清空。您的解决方案非常适合显示未选择的值,但这不是我想要的。
      • 在这种情况下,你为什么不能检查数组中的值是否存在于函数randomize()中?还有其他要求吗?
      • 我可以那样做,我现在就那样做。但我想要一些更好的(也许是开箱即用的角度)解决方案,因为我的真实世界“randomize()”函数不应该依赖于 selectedValue。感谢您的参与!
      猜你喜欢
      • 2020-02-21
      • 2016-01-05
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 2014-02-02
      相关资源
      最近更新 更多