我正在尝试将 JCrop 与 AngularJS 一起使用。我有以下指令,我需要帮助修复一下:
.directive('imgCropped', function() {
return {
restrict: 'E',
replace: true,
scope: { src:'@', selected:'&' },
link: function(scope,element, attr) {
var myImg;
var clear = function() {
if (myImg) {
myImg.next().remove();
myImg.remove();
myImg = undefined;
}
};
scope.$watch('src', function(nv) {
clear();
if (nv) {
element.after('<img />');
myImg = element.next();
myImg.attr('src',nv);
$(myImg).Jcrop({
trackDocument: true,
onSelect: function(x) {
/*if (!scope.$$phase) {
scope.$apply(function() {
scope.selected({cords: x});
});
}*/
scope.selected({cords: x});
},
aspectRatio: 1,
boxWidth: 400, boxHeight: 400,
setSelect: [0, 0, 400, 400]
});
}
});
scope.$on('$destroy', clear);
}
};
})
问题是 JCrop 没有正确检测到真实的图像大小,我需要添加一个 trueSize 选项,我知道如何做的唯一方法是将 Jcrop 调用包装在回调中,看起来很讨厌。
另外,如果我在 onSelect 回调中使用 scope.$apply ,我会收到 $digest already in progress 错误。这是为什么 ?
编辑:我可以使用以下代码成功获得真实的图像大小,但必须有更好的方法来做到这一点
.directive('imgCropped', function() {
return {
restrict: 'E',
replace: true,
scope: { src:'@', selected:'&' },
link: function(scope,element, attr) {
var myImg;
var clear = function() {
if (myImg) {
myImg.next().remove();
myImg.remove();
myImg = undefined;
}
};
scope.$watch('src', function(nv) {
clear();
if (nv) {
element.after('<img />');
myImg = element.next();
myImg.attr('src',nv);
var temp = new Image();
temp.src = nv;
temp.onload = function() {
var width = this.width;
var height = this.height;
$(myImg).Jcrop({
trackDocument: true,
onSelect: function(x) {
/*if (!scope.$$phase) {
scope.$apply(function() {
scope.selected({cords: x});
});
}*/
scope.selected({cords: x});
},
aspectRatio: 1,
boxWidth: 400, boxHeight: 400,
setSelect: [0, 0, 400, 400],
trueSize: [width, height]
});
}
}
});
scope.$on('$destroy', clear);
}
};
})