我在AngularJS 1.0.8中有一个名为custom-check-box-enquire的指令。该指令位于过滤器列表中。当用户单击过滤器时,指令应更改样式。在changeIconCheck函数内部,这工作正常。但是,该过滤器是使用已选择的一些过滤器进行初始化的,因此应突出显示那些过滤器。我试图在init方法中突出显示那些过滤器,以检查属性ID是否包含在过滤器列表中。但是,当angular对指令进行求值并首次执行init方法时,id属性仍然未定义。请查看示例代码。
.directive('customCheckBoxEnquire', function() {
function link(scope, element, attrs) {
function init() {
var selectedStates = scope.filter.states;
console.log("States=" + selectedStates);
var index = selectedStates.indexOf(parseInt(attrs.id));
if (index != -1) {
element.addClass('selected');
var checkElement = element.children('.fa-icon-check-empty');
checkElement.removeClass('fa-icon-check-empty').addClass('fa-icon-check');
}
}
function changeIconCheck() {
init();
element.click(function() {
if (element.hasClass('selected')) {
element.removeClass('selected');
var checkElement = element.children('.fa-icon-check');
checkElement.removeClass('fa-icon-check').addClass('fa-icon-check-empty');
} else {
element.addClass('selected');
var checkElement = element.children('.fa-icon-check-empty');
checkElement.removeClass('fa-icon-check-empty').addClass('fa-icon-check');
}
});
}
changeIconCheck();
}
return {
link: link
};
})
<li id="{{state.id}}" ng-repeat="state in enquireStates" class="cursor-pointer"
ng-click="onFilterState(state.id)" custom-check-box-enquire>
<i class="fa-icon-check-empty"></i>
{{state.name | translate}}
</li>
答案 0 :(得分:2)
我明白了。我观察到了该属性。
attrs.$observe('id', function(val) {#do whatever});
有关更多信息,请参见AngularJS Directive Attributes API Reference - $observe