我尝试使用canvas
directive
来实施进度条
我和elrady通过JS对象
这是非角度方式:
function progressBar(id,contentDiv)
{
this.id = id;
this.height = 2;
this.width = 200;
this.backColor = "#383838";
this.foreColor = "#61650c";
this.value = 0;
this.context = null;
this.backToZero = true;
this.create = function ()
{
var str = "";
str += "<div class='progressBarDiv' id='" + this.id + "' style='width: " + this.width + "px;'>";
str += "<canvas id='canvas_" + this.id + "' class='progressBarCanvas' width='" + this.width + "' height='" + this.height + "' style='width: " + this.width + "px;'/>";
str += "</div>";
$("#" + contentDiv).html(str);
this.drawingCanvas = document.getElementById('canvas_' + this.id);
this.context = this.drawingCanvas.getContext('2d');
this.draw();
}
this.draw = function ()
{
var ctx = this.context;
ctx.fillStyle = this.backColor;
ctx.fillRect(0, 0, this.width, this.height);
var pos = this.value / 100 * this.width;
ctx.fillStyle = this.foreColor;
ctx.fillRect(0, 0, pos, this.height);
}
this.setValue = function (value)
{
this.value = value;
if (value >= 100)
{
if (this.backToZero)
{
this.value = 0;
}
}
this.draw();
}
}
我试图用angular指令做同样的事情。 在这里我到目前为止:
KApp.directive("kProgress", function ()
{
return {
restrict: 'E',
scope: {
progressStatus: '=progress',
progressWidth:'@',
progressHeight:'@',
progressId:'@'
},
template: "<div class='progressBarDiv' style='width: " + {{progressWidth}} + "px;'>"
+"<canvas id='canvas_" + {{progressId}} + "' class='progressBarCanvas' width='" + {{progressWidth}} + "' height='" + {{progressHeight}} + "' style='width: " + {{progressWidth}} + "px;'/>"
+"</div>",
link: function(scope, element, attrs) {
scope.$watch(attrs.progressStatus, function(value) {
//Change the canvas (from the template)
});
}
};
});
我的问题是:如何从模板中获取(或有权访问)canvas元素,并根据progressStatus
属性(来自外部控制器)来操作它。我需要kProgress
指令的行为与非角度解决方案完全相同。
答案 0 :(得分:5)
我认为您上面的主要问题是您正在关注attrs.progressStatus
,而不仅仅是关注progressStatus
。这有效:
var module = angular
.module('progressBarApp', [])
.directive("progressBar", function ()
{
return {
restrict: 'E',
scope: {
progress: '=',
progressId: '@'
},
template: "<canvas id='pgcanvas' width='400' height='30' background-color: #F00'/>",
link: function(scope, element, attrs) {
console.log(element);
scope.canvas = element.find('canvas')[0];
scope.context = scope.canvas.getContext('2d');
scope.$watch('progress', function(newValue) {
barWidth = Math.ceil(newValue / 100 * scope.canvas.width);
scope.context.fillStyle = "#DDD";
scope.context.fillRect(0, 0, scope.canvas.width, scope.canvas.height);
scope.context.fillStyle = "#F00";
scope.context.fillRect(0, 0, barWidth, scope.canvas.height);
});
}
};
});
......并且在一个小提琴中:http://jsfiddle.net/e7pbc7y5/23/。只需更改文本框中的值,它就会更新进度条。
答案 1 :(得分:-1)
这是一个直接的用例,请参阅“创建通信指令”部分。 https://docs.angularjs.org/guide/directive