我有一个角度指令来根据屏幕大小更改图像源。它可以正常使用静态内容,但它不能使用来自$ http请求的动态数据。
我的指示
app.directive("changeOnScreenResize", ["$window", function($window) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
$window.onresize = function() {
changeImage();
scope.$apply();
}
changeImage();
function changeImage() {
scope.screenWidth = $window.innerWidth;
if(scope.screenWidth <= 600) {
elem.attr('src', attrs.small);
console.log(attrs.small);
}
else {
elem.attr('src', attrs.big);
}
}
}
};
}]);
来自$ http的动态数据通话
<div ng-repeat="slideContent in vm.slides track by $index" >
<div ng-bind-html="vm.getHtml(slideContent)"></div>
</div>
与来自$ http请求和指令的数据相同的静态数据在这种情况下正常工作。
<img change-on-screen-resize src="abc.jpg" small="xyz.jpg" big="abcd.jpg" >
答案 0 :(得分:1)
问题是您正在向范围中插入新的HTML,而无需重新编译应用程序。因此,angular不知道子元素中的change-on-screen-resize
是什么意思。
请参阅此工作演示:http://plnkr.co/edit/NJJjgoMuhnDRjnE2jNYE?p=preview
在使用新HTML成功加载DOM后,您需要创建一个新指令来调用$compile
。
app.directive('bindUnsafeHtml', ['$compile',
function($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'bindUnsafeHtml' expression for changes
return scope.$eval(attrs.bindUnsafeHtml);
//return element.children();
},
function(value) {
// when the 'bindUnsafeHtml' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current scope
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
}
]);