摘要
我正在使用配置replace: true
的第三方指令。
我希望每次用户单击按钮时重新编译该指令。我没有运气就尝试过几件事情。例如,我尝试在我自己的指令中包装Cloudinary指令,但我似乎无法得到它。任何帮助将不胜感激。
依赖关系
"angular": "1.6.2",
"cloudinary-core": "^2.5.0",
"cloudinary_ng": "^1.1.1",
控制器
$scope.rotate = (leader) => {
leader.cloudinary_angle = {
'0': '90',
'90': '180',
'180': '270',
'270': '0'
}[leader.cloudinary_angle] || '0';
};
查看
<div ng-repeat="leader in leaders">
<a href="#" ng-click="rotate(leader)">Rotate</a>
<cloudimage leader="leader"></cloudimage>
</div>
没有工作#1
angular.module('app').directive('cloudimage', ($compile) => {
return {
restrict: 'E',
replace: false,
scope: {
leader: '='
},
link: (scope, element) => {
let cloudinaryImage = $compile('<cl-image angle="' + scope.leader.cloudinary_angle + '"' +
' crop="fit"' +
' format="jpg"' +
' height="150"' +
' public-id="' + scope.leader.cloudinary + '"' +
' quality="80"' +
' width="150"' +
'></cl-image>'
)(scope);
element.html(cloudinaryImage[0]);
scope.$watch('scope.leader.cloudinary_angle', (cloudinaryImage) => element.html(cloudinaryImage[0]));
}
};
});
没有工作#2
angular.module('app').directive('cloudimage', ($compile) => {
return {
restrict: 'E',
replace: false,
scope: {
leader: '='
},
template: '<cl-image crop="fit" format="jpg" height="150" angle="{{angle}}" public-id="{{id}}" quality="80" width="150"></cl-image>',
link: (scope, element) => {
scope.angle = scope.leader.cloudinary_angle || 0;
scope.id = scope.leader.cloudinary;
}
};
});
没有工作#3
我可以装饰第三方指令以使其replace: false
,但这会打破它的转换。
angular.module('app').config(['$provide', function($provide) {
$provide.decorator('clImageDirective', function($delegate) {
var directive = $delegate[0];
directive.replace = false;
return $delegate;
})
}]);
答案 0 :(得分:1)
#1
不起作用,因为html()
需要字符串,而不是DOM元素。不应将cloudinaryImage
元素转换为字符串,因为这会破坏有关该元素的信息。
应该是:
scope.$watch('scope.leader.cloudinary_angle', (cloudinaryImage) => {
element.empty().append(cloudinaryImage)
});
答案 1 :(得分:0)
脏兮兮的时间......您可以使用单个元素的数组上的ng-repeat重新编译任何内容(包括一次性绑定,任何指令):
<body ng-controller="MainCtrl" ng-init="arr = [{}]">
<button ng-click="arr = [{}]">Recompile</button>
<p test ng-repeat="o in arr"></p>
</body>
其中test指令是
app.directive('test', function() {
return {
replace: true,
template: '<span>hello</span>',
link: function() {
console.log('I am linked');
}
}
})
P.S。你可以用ng-if做同样的事情,但是你需要2个摘要。 P.P.S.我同意这有点奇怪。