0

我试图创建一个与进度条相对应的 AngularJS 组件。这是为这个问题创建的 JSFiddle http://jsfiddle.net/Lvc0u55v/6725/

这是我的应用程序和组件定义:

var myApp = angular.module('myApp',[]);

myApp.controller('TestController', function($scope) {
    $scope.total = 20;
    $scope.count = 15;

    $scope.changeTotal = function(value){$scope.total += value};
    $scope.changeCount = function(value){$scope.count += value};
});

myApp.component('progressBar', {
    bindings: {
        percentage: '=',
    },
    controller: function() {
        this.width = this.percentage * 100;
    },
    template: '<div class="progressBar">\
            <div class="inner" style="width: [[$ctrl.width]]%"></div>\
        </div>',
});

以及以下 HTML 代码:

<div ng-app="myApp">
  <div ng-controller="TestController">
    Total: {{total}}, <button ng-click="changeTotal(-1)">-</button><button ng-click="changeTotal(+1)">+</button><br/>
    Count: {{count}}, <button ng-click="changeCount(-1)">-</button><button ng-click="changeCount(+1)">+</button><br/>
    Percentage: {{count / total}}%<br/>
    <br/>

    <progress-bar percentage="{{count / total}}"></progress-bar>

  </div>
</div>

尽管在组件控制器中定义了width属性,AngularJS 却无法在定义的模板中找到它。

自从我刚开始学习 AngularJS 以来,我很难有效地调试这段代码。

4

1 回答 1

1

当您=在组件中使用(双向绑定)时,您不应该{{}}在百分比属性值中使用。直接计算的值可以传递给percentage()括号括起来的属性。

在为显示进度条绑定百分比时,您可以使用带有已传递给组件ng-style的值的指令。$ctrl.percentagebindings

HTML

<progress-bar percentage="{{(count / total)}}"></progress-bar>

指令模板

template: '<div class="progressBar">\
        <div class="inner" ng-style="{ width: $ctrl.percentage+\'%\'}"></div>\
    </div>',

JSFiddle 这里

于 2016-07-11T16:34:00.570 回答