我想为一个输入元素做一个指令,它会检查相应的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(如果没有办法,我可能需要)。如果有办法推迟,请告诉我。
答案 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>
总之,搜索input
框中的ng-change
指令触发指令范围方法,该方法将值与匹配的所有数据项进行比较。如果它找不到,ng-class
指令会导致notfound
类出现在元素上。
作为一项规则,在编写Angular应用程序时,如果您发现自己已经在DOM中存在元素,那么您将在其他地方找到更好的解决方案。使用DOM的变通办法在您的代码中应该很少或根本不存在。
我希望我的代码(和Plunker)为您提供一个模板来对您进行更改。如果此解决方案存在问题,请在评论中告诉我。如果您对将其应用于代码有一般性问题,请随时与我私下联系。