我想从指令中的链接函数访问模板的DOM对象,但我不能。我想访问这个canvas对象,在一些文件上传后更改它
MakeApp
.directive('fileUploaderDir', function ($location) {
return {
restrict: 'A',
scope: {
},
template: function (elem , attr) {
if(attr.maxNumberFile<=1){
return'<tbody ng-init="changeCanvas">' +
'<tr ng-repeat="item in uploader.queue">' +
'<td ><strong>{{ item.file.name }}</strong>' +
'<canvas id="canvasImgUpload"/>' +
'</td>' +
'<td ng-show="uploader.isHTML5" nowrap>{{ item.file.size/1024/1024|number:2 }} MB</td>' +
'<td ng-show="uploader.isHTML5">' +
'<div class="progress" style="margin-bottom: 0;">' +
'<div class="progress-bar" role="progressbar" ng-style="{ \'width\': item.progress + \'%\' }"></div>' +
'</div>' +
'</td>' +
'<td class="text-center">' +
'<span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>' +
'<span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>' +
'<span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>' +
'</td>' +
'<td nowrap>' +
'<button type="button" class="btn btn-success btn-xs" ng-click="item.upload()" ng-disabled="item.isReady || item.isUploading || item.isSuccess">' +
'<span class="glyphicon glyphicon-upload"></span> Upload' +
'</button>' +
'<button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()" ng-disabled="!item.isUploading">' +
'<span class="glyphicon glyphicon-ban-circle"></span> Cancel' +
'</button>' +
'<button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">' +
'<span class="glyphicon glyphicon-trash"></span> Remove' +
'</button>' +
'</td>' +
'</tr>' +
'</tbody>'
}
else {
return '<div class="modal-container" data-toggle="modal" data-target="#modal-h">'
}
},
link : function($scope, element, attrs) {
// $scope.canvasImgUpload = element.getElementById('canvasImgUpload');
// $scope.canvasImgUpload = element.find('canvas')[0];
// $scope.contextImgUpload = $scope.canvasImgUpload.getContext('2d');
$scope.changeCanvas=function(){
$scope.canvasImgUpload = angular.element(document.querySelector('#canvasImgUpload'));
console.log("canvass" , $scope.canvasImgUpload);
}
$scope.$watch('uploader.queue' , function () {
alert('queue changeeee');
})
}
我想在模板中访问canvas但返回空对象!谁能告诉我为什么?
答案 0 :(得分:0)
原因可能是您在插入DOM元素之前尝试访问它。
解决方案可以是在模板中使用 ng-init 。 例如:
HTML模板:
<div class="modal-container" data-toggle="modal" data-target="#modal-h"
ng-init='changeCanvas()'>
<canvas id="canvas"></canvas>
</div>
指令链接脚本:
link : function($scope, element, attrs) {
$scope.changeCanvas=function(){
$('#canvas').doSomething();
}
}