从angularjs更改bootstrap进度条宽度

时间:2013-12-31 17:48:08

标签: javascript html css angularjs twitter-bootstrap

我是Angularjs的新手,当我的控制器中的值发生变化时,我正在尝试更新进度条的宽度。

我有类似的东西:

<span id="percentage">$ {{getTotal()}} ({{getPercentage()}}%)</span>
<div class="progress-bar progress-bar-warning" 
  role="progressbar" aria-valuenow="10" aria-valuemin="0" 
  aria-valuemax="100" style="width: 10%">
    <span class="sr-only">10% Complete (warning)</span>
</div>

我在控制器中有类似的东西:

$scope.total = 254.78;
$scope.threshold = 15000;

$scope.getPercentage = function () {
    return (($scope.total * 100) / $scope.threshold).toFixed(2);
}
$scope.getTotal = function () {
    return $scope.total;
}

如何更新进度条的宽度值?

谢谢, 阿尔贝托。

5 个答案:

答案 0 :(得分:46)

ng-style指令可以解决问题。

<span id="percentage">$ {{getTotal()}} ({{getPercentage()}}%)</span>
<div class="progress-bar progress-bar-warning" 
  role="progressbar" aria-valuenow="{{getPercentage()}}" aria-valuemin="0" 
  aria-valuemax="100" ng-style="{width : ( getPercentage() + '%' ) }">
    <span class="sr-only">{{getPercentage()}}% Complete (warning)</span>
</div>

答案 1 :(得分:3)

我会使用一个指令,它负责自己计算宽度。

module.directive("progressbar", function () {
    return {
        restrict: "A",
        scope: {
            total: "=",
            current: "="
        },
        link: function (scope, element) {

            scope.$watch("current", function (value) {
                element.css("width", scope.current / scope.total * 100 + "%");
            });
            scope.$watch("total", function (value) {
                element.css("width", scope.current / scope.total * 100 + "%");
            })
        }
    };
});

http://jsfiddle.net/rGWUR/10/

答案 2 :(得分:2)

嗯,你应该这样做:

<div class="progress-bar progress-bar-warning" 
  role="progressbar" aria-valuenow="{{getPercentage()}}" aria-valuemin="0" 
  aria-valuemax="100" style="width: {{getPercentage()}} %">
    <span class="sr-only">{{getPercentage()}}% Complete (warning)</span>
</div>

答案 3 :(得分:2)

我认为更好的解决方案是使用Angle -UI进度条而不是尝试重新发明轮https://angular-ui.github.io/bootstrap/#/progressbar

<uib-progressbar value="50"></uib-progressbar>

答案 4 :(得分:1)

您可以编写自定义ng-style

 <div class="progress-bar progress-bar-warning"
    role="progressbar" 
    aria-valuenow="10"
    aria-valuemin="0"
    aria-valuemax="100" 
    ng-style="percentageStyle">
        <span class="sr-only">10% Complete (warning)</span>
 </div>

并在控制器中:

 $scope.percentageStyle = {
   width : $scope.getPercentage() + '%'     
 };

演示 Fiddle