我今天第一次使用指令,并试图构建一个可重用的进度条指令(基于Bootstra3.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%。是否有更好的方法来完成像这样的动态更新内容,或者当涉及到范围或一些愚蠢的内容时,我是遗漏了什么?
发布于 2013-10-25 00:37:28
您在attrs.width上使用了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
发布于 2013-10-25 01:52:27
在您的指令中,需要使用
scope: { width: '=' }=这类参数表示在指令范围内创建双向参数的角度,因此,如果在指令中更改它的值,则控制器将受到影响,如果在控制器中更改此值,则会反映指令。
https://stackoverflow.com/questions/19579115
复制相似问题