2014-10-11 119 views
0

我試圖改變內部指令的範圍數據,我得到thi錯誤:[$ rootScope:inprog] $ digest已在進行中。 我試過$超時但它沒有幫助。 我遍歷類別數組並顯示麪包屑(例如something1> something2> something3> something4),它們作爲字符串包含在category.name中。

<div ng-repeat="category in categories"> 
     <div breadcrumbs="breadcrumbs" category="category"> 
     <span class="description" id="name_{{category.id}}" >{{category.name}}</span> 
     <div> 
</div> 

我想,當這個div的容器收縮是麪包屑響應變成這種形式的「something1> ...> something3> something4」或本「something1> ...> something4」這取決於有多寬容器是多少,麪包屑是多少。

爲了做到這一點,我創建了一個名爲'breadcrumbs'的指令,它檢查相關元素的大小是否大於20,這意味着breadcrumb必須被縮小。 這裏是指導..

angular.module('demo') 
.directive('breadcrumbs', [ '$log', '$window', function($log, $window) { 
    'use strict'; 

    return { 
     restrict: 'A', 
     link: function(scope, elem, attrs){ 
       scope.getElemHeight = function() { 
        return elem.height(); 
       } 

       scope.shortenBreadcrumb = function(){ 
        if (scope.getElemHeight() > 20){ 
         console.log(scope.getElemHeight()); 
         var breadcrumbArry = scope.category.name.split(" > "); 
         var i = 1; 
       //remove breadcrumb by breadcrumb until whole breadcrumbs string fits the container 
       while ((scope.getElemHeight() > 20) && (breadcrumbArry.length > 3)){ 
          if (i == 1) breadcrumbArry[i] = "..." 
          else breadcrumbArry.splice(2, 1); // remove 1 element on index 2 
          scope.category.name = breadcrumbArry.join(" > "); 
          i++; 
          scope.$apply(); 
       } 
        } 

       } 

       // Set on load 
       scope.$watch(scope.getElemHeight, function (newValue, oldValue) { 
        scope.shortenBreadcrumb(); 
        console.log("LOOOOOOAD "+scope.category.id); 
       }, true); 

       // Set on resize 
       angular.element($window).bind('resize', function() { 
        scope.category.name = scope.category.fullBreadcrumb; 
        scope.shortenBreadcrumb(); 
        scope.$apply(); 

       });     
     }, 
     scope: { 
      category: '=' 
     } 
    } 
}]); 

它運作良好的負載和窗口大小調整,但我不斷收到控制檯上提到的錯誤。我試圖用while循環中的$ timeout,但我然後我的瀏覽器崩潰,因爲它永遠等待,永遠不會進入超時函數,可能是因爲它是從$ scope.watch調用的。 我真的需要幫助,因爲我沒有想法如何解決它。

這裏是工作示例http://jsfiddle.net/radiolaria/0btwgmzj/29/如果您檢查控制檯輸出,您會看到錯誤。

+0

最有可能的罪魁禍首是$手錶,也爲你的手錶$語法不正確... – harishr 2014-10-11 16:43:28

+0

好吧,當我從刪除「真」看它是一樣的。你還會建議什麼?如何解決這個問題? – radiolaria 2014-10-11 20:01:47

+0

嘗試刪除while循環... – harishr 2014-10-12 12:09:46

回答

0

刪除這兩個$scope.$apply電話,並更換電話縮短麪包屑與scope.$evalAsync(scope.shortenBreadcrumb);

+0

你可以接受/ upvote的答案,如果它的工作?? – harishr 2014-10-24 17:33:33