动态更新指令(1.2 rc3)

时间:2013-10-25 00:30:21

标签: javascript angularjs angularjs-directive

我今天第一次玩指令并且正在尝试构建一个可重用的进度条指令(基于Bootstrap 3.0),我可以根据值动态填充或清空。指令定义如下:

directive('progressBar', function () {
    var success = 'progress-bar progress-bar-success';
    var warning = 'progress-bar progress-bar-warning';
    var danger = 'progress-bar progress-bar-danger';

    var setCssStyling = function (width) {
        if (width >= 50) {
            return success;
        } else if (width >= 20) {
            return warning;
        } else {
            return danger;
        }
    }

    var formatWidth = function (width) {
        return 'width: ' + width + '%';
    }

    return {
        restrict: 'E',
        scope: {},
        template: '<div class="progress progress-striped active">' +
            '<div ng-class="cssStyle" role="progressbar" style="{{ width }}"></div>' +
            '</div>',
        link: function (scope, element, attrs) {
            if (attrs.width) {
                scope.width = formatWidth(attrs.width);
            } else {
                scope.width = formatWidth(0);
            }
            scope.$watch(attrs.width, function (newVal) {
                scope.width = formatWidth(newVal);
                scope.cssStyle = setCssStyling(newVal);
            });
        }
    }
});

根据这些测试用法,这完全符合计划:

<progress-bar width="100"></progress-bar>
<progress-bar width="45"></progress-bar>
<progress-bar width="15"></progress-bar>

我希望能够将width属性动态绑定到控制器中的更改值,以使进度条的宽度和样式移动。我尝试绑定到我的控制器中每秒都改变的值:

<progress-bar width="{{ today.seconds }}"></progress-bar>

但是,当我检查该进度条的范围时,宽度始终设置为width: undefined%。有没有更好的方法来完成动态更新这样的内容,还是我在范围或某些愚蠢的事情上遗漏了什么?

2 个答案:

答案 0 :(得分:1)

您在scope.$watch上使用attrs.width,这意味着它不应该是插值。所以你应该只做<progress-bar width="today.seconds"></progress-bar>

如果您希望能够使用插值,则使用scope.$observe,并且还需要解析宽度(因为插值将返回一个字符串)。

更新:由于您已设置隔离范围(scope: {}),因此需要在范围哈希对象中绑定width

return {
    restrict: 'E',
    scope: { width: '='},
    template: '<div class="progress progress-striped active">' +
        '<div ng-class="cssStyle" role="progressbar" style="{{ cssWidth }}"></div>' +
        '</div>',
    link: function (scope, element, attrs) {
        scope.cssWidth = '';
        scope.$watch('width', function (newVal) {
            scope.cssWidth = formatWidth(newVal);
            scope.cssStyle = setCssStyling(newVal);
        });
    }
}

当然,如果在您的上下文中有意义,您也可以放弃隔离范围。您也可以将cssWidth全部放在一起,只需在style属性中进行格式化。

http://plnkr.co/edit/Zx1fgHYyXuxByHH6YorP

答案 1 :(得分:1)

在您的指令中,您需要使用

scope: { width: '=' }

=这种参数表示在您的指令范围内创建一个双向参数,因此,如果您在指令中更改它的值,您的控制器将受到影响,如果您更改了此值控制器你的指令将被反映