2014-08-27 62 views
2

當進度條中的「max」值改變時,進度條不會更新其相對進度。AngularJS Bootstrap進度條最大變化

<progressbar max="max" value="dynamic"><span style="color:black; white-space:nowrap;">{{dynamic}}/{{max}}</span></progressbar> 

通過使用一種方法來隨機化的最大值

$scope.random = function() { 
var other = Math.floor((Math.random() * 100) + 100); 
var type; 

if (value < 25) { 
    type = 'success'; 
} else if (value < 50) { 
    type = 'info'; 
} else if (value < 75) { 
    type = 'warning'; 
} else { 
    type = 'danger'; 
} 

$scope.showWarning = (type === 'danger' || type === 'warning'); 
$scope.max = other; 
$scope.type = type; }; 

我有一個醜陋的解決辦法,但我想知道是否有更合適的方法

<progressbar value="dynamic/max*100"><span style="color:black; white-space:nowrap;">{{dynamic}}/{{max}}</span></progressbar> 

見例在這裏: http://plnkr.co/edit/urZH8i2sJUeeTgIJ7JWU?p=preview

回答

0

的一種方法是在配置階段來裝飾經由$provide.decorate()progressbarbar指令。在裝飾者內部,您需要通過attr.$observe()添加觀察者以觀察屬性,並使用其內插值觀察屬性dynamicMax。對於觀察者回調必須更新以下分離的變量:

[] scope.max

參考文獻:

https://github.com/angular-ui/bootstrap/blob/master/src/progressbar/progressbar.js#L13

[] 範圍。%的

參考:

https://github.com/angular-ui/bootstrap/blob/master/src/progressbar/progressbar.js#L23 https://github.com/angular-ui/bootstrap/blob/master/src/progressbar/progressbar.js#L61 https://github.com/angular-ui/bootstrap/blob/master/src/progressbar/progressbar.js#L78 https://github.com/angular-ui/bootstrap/blob/master/template/progressbar/progressbar.html


PLUNKER DEMO

JAVASCRIPT

.config(function($provide) { 

    var progressDecorator = function($delegate) { 
     var directive = $delegate[0]; 
     var compile = directive.compile; 
     var link = directive.link; 

     directive.compile = function() { 
     compile.apply(this, arguments); 

     return function(scope, elem, attr, ctrl) { 
      link.apply(this, arguments); 

      if(angular.isDefined(attr.dynamicMax)) { 
      attr.$observe('dynamicMax', function(max) { 
       scope.max = max; 
       scope.percent = +(100 * scope.value/max).toFixed(2); 
      }); 
      } 

     }; 
     }; 

     return $delegate; 
    }; 

    $provide.decorator('progressbarDirective', progressDecorator); 
    $provide.decorator('barDirective', progressDecorator); 
    }); 

HTML

使用

<progressbar dynamic-max="{{max}}" value="value"> 
    <span style="color:black; white-space:nowrap;">{{value}}/{{max}}</span> 
</progressbar> 

注意,有一個叫dynamic-max新的屬性。這是在觀察中更改最大值的屬性,如果要具有動態最大值,則使用此屬性代替max。注意,你需要指定一個插值(價值必須被包裹在一個{{}}

DECORATING DIRECTIVES REFERENCE

+0

謝謝,這似乎是最有效的解決方案,以保持進度欄清潔,特別是在我將不止一次使用dynamic-max的情況下。 – Meredori 2014-08-28 02:53:29

0

看着你example.js,進度條不會自動更新的原因是因爲您的$scope.dynamic = value;已註釋掉。取消註釋它,你的進度條似乎工作正常。另外,請記住,max總計進度的值(默認爲100),所以我不確定爲什麼您希望它會動態更改; value是應該改變的。

看看這個demoexample.js

編輯:根據OP的評論修復plnkr鏈接。解決這個問題

+0

的問題是,我使用他們作爲「健康網吧」的實際執行情況等如果最大健康狀況增加,酒吧開始做一些奇怪的事情,我談到了。 此外,你犯了一個錯誤連接plnkr。 – Meredori 2014-08-28 02:54:26