2016-05-13 99 views
1

我的指令:AngularJS指令有時不叫

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; 
       //}); 
      } 
     }); 
    } 
}; 
}); 

有時指令調用,有時沒有。它可能位於相同的HTML文件中,其中一些元素可以具有標記,並且對於某些元素來說該指令被調用,而對於其他元素則不是。

focus-me="true" 

我甚至有兩個不同的HTML文件具有相同的代碼,但對於其中一個指令從不調用。例如,此代碼可以在一個HTML文件中工作,而不在另一箇中。

<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> 

什麼可能導致這種情況?控制器是否對指令做任何事情?這感覺很奇怪

+0

http://stackoverflow.com/questions/14833326/how-to-set-focus- on-input-field >> $超時似乎需要給模態時間渲染。 –

+0

這並沒有解決我的問題。 –

回答

0

好了,所以我解決我的問題。 沒有調用指令的元素實際上被調用,但是在錯誤的時間/視圖中。所以無論何時加載視圖(元素所在的位置),focus-me指令都不會被調用,因爲它已經在之前的視圖中調用過。實質上,我不得不將ng-show改成ng-if。

此:

<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> 

要這樣:

<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> 

0

您正在添加一個$watch不會改變的變量,除了當您從指令中更改它時。你有沒有傳遞給focus-me?如果沒有,那麼你可以做掉的手錶,只需使用以下命令:

ppm.directive('focusMe', function($timeout) { 
return { 
    link: function(scope, element, attrs) { 
     element.focus(); 
    } 
}; 
}); 
<button focus-me>Some text</button> 
+0

這並沒有解決我的問題。 Focus-Me標籤正在處理某些元素,而有些則不是。 –