2013-07-30 102 views
0

我遇到了一個問題,當我更新DOM時,會將數據傳遞給我的指令進行更新。該指令突出顯示了sidenav中的活動選項卡與他們在頁面上滾動到的位置之間的關係。這是我做過的fiddle example在角度指令中更新數據

在我的本地網站上,有很大的部分有條件地顯示或隱藏,用戶可以經常更改此項。因此,這改變了我存儲在resultsSections中的元素ID的位置。當職位發生變化時,他們不會在指令中更新。

<script type="text/javascript"> 
$scope.getResultsSectionPosition = function() { 
    var resultsSections = {}; 
    $('.results-heading').each(function() { 
     resultsSections[this.parentNode.id] = $(this).offset().top; 
    }); 
    console.log(resultsSections); 
    return $scope.resultsSections = resultsSections; 
} 
$scope.getResultsSectionPosition(); 
</script> 

我已經通過調用$scope.getResultsSectionPosition()重新初始化本地站點 - 新的偏移量存儲在resultsSections,但該指令仍保持初始值。 如何強制指令使用最活躍的數據?

myApp.directive('navActive', function() { 
return function(scope, element, attrs) { 

     var height = $(window).height(), 
      section = 0; 
     $(window).bind("scroll", function() { 
      var position = $(this).scrollTop(); 
      for (section in scope.resultsSections) { 
       if (position + height - 50 >= scope.resultsSections[section]) { 
        $('li').removeClass('results-nav-active'); 
        $('#nav_' + section).addClass('results-nav-active'); 
       }; 
      }; 
     }); 
    }; 
}) 

我試過期運用scope.$watch('resultsSections", function(){...}),但都沒有取得成功這一點。

回答

2

你應該BA能夠使用$手錶,但你也可以使用分離scope屬性,然後直接通過您的controlle $範圍變量的指令

我調整一點你的代碼,我加了一些控制檯。登錄以查看會發生什麼,您可以在這裏看到http://jsfiddle.net/DotDotDot/uC2dP/14/

我在頂部添加了一個按鈕,強制修改位置,以便查看指令中的反響,並在指令中添加了一個console.log()與調用位置滾動。此外,您的指令現在有一個孤立的範圍,與resultsSections綁定在HTML

return { 
    scope:{resultsSections:"=sections"}, 
    link:function(scope, element, attrs) { 


    var height = $(window).height(), 
     section = 0; 
    $(window).bind("scroll", function() { 
     var position = $(this).scrollTop(); 
     console.log(scope.resultsSections) 
     for (section in scope.resultsSections) { 
      if (position + height - 50 >= scope.resultsSections[section]) { 
       $('li').removeClass('results-nav-active'); 
       $('#nav_' + section).addClass('results-nav-active'); 
      }; 
     }; 
    }); 
} 
} 

,並在HTML中給出的參數:

<section nav-active sections="resultsSections"> 

你可以看到,如果你點擊按鈕,然後滾動,在該指令的位置是否正確更新

玩得開心

+0

我試着做類似的(和公正又試了一次)的東西,但我得到一個錯誤'錯誤:錯誤而插值:...'。但是如果我註釋掉'scope:[resultsSections:'=節'}',那麼它就會消失./ – EnigmaRM

+0

這很奇怪,它在小提琴中運行良好,而且我最近使用了類似的東西。該錯誤在您評論時消失,該錯誤必須正常,但該值不會更新。然而,當我嘗試在屬性中傳遞一個函數時,我有這個錯誤或類似的東西,你是否嘗試過使用變量或函數? – DotDotDot

+0

我正在傳遞變量'resultsSections',它實際上存在於'$ rootScope'中 – EnigmaRM