Change bootstrap progress-bar width from angularjs

2020-02-03 12:49发布

I'm new in Angularjs and I am trying to update the width of a progress bar when a value in my controller change.

I have something like:

<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>

And I have in my controller something like:

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

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

How do I update the width value of the progress bar?

Thanks, Alberto.

5条回答
该账号已被封号
2楼-- · 2020-02-03 13:13

ng-style directive would do the trick.

<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>
查看更多
三岁会撩人
3楼-- · 2020-02-03 13:13

I think que the better solution is to use Angle -UI progress bar instead trying to reinvent the wheel https://angular-ui.github.io/bootstrap/#/progressbar.

<uib-progressbar value="50"></uib-progressbar>
查看更多
Fickle 薄情
4楼-- · 2020-02-03 13:27

You can write custom 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>

and in controller:

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

Demo Fiddle

查看更多
疯言疯语
5楼-- · 2020-02-03 13:30

Well, you should do something like this:

<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>
查看更多
倾城 Initia
6楼-- · 2020-02-03 13:31

I would use a directive for this, that is responsible for calculating the width by itself.

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/

查看更多
登录 后发表回答