2014-10-11 54 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