我正在尝试创建一个Twitter共享按钮指令,该指令会根据父模型进行更改
app.directive('twitterShare', function() {
return {
restrict: 'A',
template: "<a href=\"https://twitter.com/share\" data-count=\"none\" class=\"twitter-share-button\" data-text=\"{{text}}\" data-lang=\"pt-BR\"></a>",
scope: {
text: '=twitterShare'
},
link: function($scope, $element, $attrs, $model) {
return $scope.$watch('text', function(value) {
//??
});
}
};
});和指令
<div twitter-share="scopeModel"></div>$scope.text正确地显示了我的$scope.scopeModel,但是由于twitter用iframe替换了a元素,元素本身就丢失了。当它改变时,我如何重新创建/重画,但应用某种油门,因为重新创建iframe是昂贵的。
尝试将其更改为
app.directive('twitterShare', function($compile, $timeout) {
return {
restrict: 'A',
scope: {
text: '=twitterShare'
},
link: function($scope, element) {
var $element;
$element = "<a href=\"https://twitter.com/share\" data-count=\"none\" class=\"twitter-share-button\" data-text=\"{{text}}\" data-lang=\"pt-BR\"></a>";
$scope.$watch('text', function(value) {
if (value != null) {
$timeout(function() {
element.html($compile($element)($scope));
typeof twttr !== "undefined" && twttr !== null ? twttr.widgets.load() : void 0;
});
}
});
}
};
});但是第二次更改$watch模型时,{{text}}占位符并没有更新。另一件奇怪的事情是,每次scopeModel更改时,$$watchers对象都会一直递增。
发布于 2013-05-04 20:26:36
答案是使用$interpolate而不是$compile。$interpolate使其能够处理字符串,并且不会像$compile那样堆叠$$watchers,而且在内存和CPU使用方面也比$compile容易得多
app.directive('twitterShare', function($interpolate, $timeout) {
return {
restrict: 'A',
scope: {
text: '=twitterShare'
},
replace: true,
template: "<div ng-bind-html-unsafe='element'></div>",
link: function($scope, element) {
var $element;
$element = "<a href=\"https://twitter.com/share\" data-count=\"none\" class=\"twitter-share-button\" data-text=\"{{text}}\" data-lang=\"pt-BR\"></a>";
$scope.$watch('text', function(value) {
if (value != null) {
$timeout(function() {
$scope.element = $interpolate($element)($scope);
typeof twttr !== "undefined" && twttr !== null ? twttr.widgets.load() : void 0;
});
}
});
}
};
});https://stackoverflow.com/questions/16368829
复制相似问题