Michael Bui Michael Bui - 6 months ago 18
HTML Question

AngularJS directive is sometimes not called

My directive:

ppm.directive('focusMe', function($timeout) {
return {
link: function(scope, element, attrs) {
scope.$watch(attrs.focusMe, function(value) {
if(value === true) {
console.log('value=',value);
//$timeout(function() {
element[0].focus();
scope[attrs.focusMe] = false;
//});
}
});
}
};
});


Sometimes the directive is called and sometimes not. It could be in the same HTML file where some elements can have the tag and for some element the directive is called and for others it is not.

focus-me="true"


I even have two different HTML files with the same code, but for one of them the directive is never called. For example this code could work in one HTML file and not in another.

<div class="row form-group">
<div class="col-xs-12" style="text-align:center;">
<button class="btn btn-default" ng-click="addMore();" tabindex="5" focus-me="true">
<span class="glyphicon glyphicon-plus button-add"></span>
Add more
</button>
</div>
</div>


What could be causing this? Does the controllers do anything with the directives? It feels weird that

Answer

Ok so I solved my issue. The elements that didn't call the directive was actually called but in the wrong time/view. So whenever the view (where the elements resided) was loaded, the focus-me directive was never called because it was already called in a previous view. In essence I had to change ng-show to ng-if.

This:

<div class="container-fluid">
<div dn-breadcrumbs dn-value="{{data.unitDn}}" ignore-levels="2" ng-show="currentStep > 0"></div>
<div ng-include="'templates/report/step1.html'" ng-controller="ReportStep1Controller" ng-show="currentStep == 0"></div>
<div ng-include="'templates/report/vri-step2.html'" ng-show="currentStep == 1"></div>
<div ng-include="'templates/report/vri-step3.html'" ng-show="currentStep == 2"></div>

To this:

<div class="container-fluid">
<div dn-breadcrumbs dn-value="{{data.unitDn}}" ignore-levels="2" ng-if="currentStep > 0"></div>
<div ng-include="'templates/report/step1.html'" ng-controller="ReportStep1Controller" ng-show="currentStep == 0"></div>
<div ng-include="'templates/report/vri-step2.html'" ng-if="currentStep == 1"></div>
<div ng-include="'templates/report/vri-step3.html'" ng-if="currentStep == 2"></div>

Comments