在选择项目中找不到模型值时,添加要输入的类

时间:2014-05-19 00:08:40

标签: javascript angularjs angularjs-directive

我想为一个输入元素做一个指令,它会检查相应的datalist,如果该值不在datalist中,则添加一个类。

由于list属性是相应id的{​​{1}},我使用的是:

datalist

HTML看起来像:

app.directive('listCheck', function() {
    return{
        restrict: 'A',
        link: function(scope, element, attrs) {
            var options = document.querySelectorAll("#"+attrs.list+">option[ng-repeat]");
            //used as this since the list shouldn't change...
            console.log(options);    // <- return []
            //although the querySelector is all right
            //[ng-repeat] is used to remove the void options
        }
    }
});

看起来,我需要将指令初始化推迟到编译完成之后,但我真的不想使用$ timeout(如果没有办法,我可能需要)。如果有办法推迟,请告诉我。

1 个答案:

答案 0 :(得分:1)

尽管我之前的评论暗示了一种方法,可以在最严格的意义上完成你想要做的事情,但我想提出一个改进措施,可以帮助你以更适合的方式完成同样的事情。角。

而不是使用DOM来检查input框的值与select选项的值,这将需要一个hack-ish解决方案,您应该比较输入的模型选项数据存储在其原始数据结构中。

控制器中的数据:

$scope.colors = [
    { name: 'Red' },
    { name: 'Orange' },
    { ... }
];

<强>指令:

.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      items: '='
    },
    templateUrl: 'my-directive.html',
    link: function(scope, elem, attrs) {
      scope.checkValue = function(search){
        // directive scope function which checks search
        // value against items array
      };
    }
  }
})

指令模板:

<div>
  <input type="text" ng-model="search" ng-change="checkValue(search)" ng-class="{notfound: notfound}" />
  <select ng-options="item.name for item in items" ng-model="selection">
    <option value>Choose an option</option>  
  </select>
</div>

index.html:

<my-directive items="colors"></my-directive>

Working Plunker

总之,搜索input框中的ng-change指令触发指令范围方法,该方法将值与匹配的所有数据项进行比较。如果它找不到,ng-class指令会导致notfound类出现在元素上。

作为一项规则,在编写Angular应用程序时,如果您发现自己已经在DOM中存在元素,那么您将在其他地方找到更好的解决方案。使用DOM的变通办法在您的代码中应该很少或根本不存在。

我希望我的代码(和Plunker)为您提供一个模板来对您进行更改。如果此解决方案存在问题,请在评论中告诉我。如果您对将其应用于代码有一般性问题,请随时与我私下联系。