这是我的指示:
module.directive('iconSwitcher', function() {
return {
restrict : 'A',
link : function(scope, elem, attrs) {
var currentState = true;
elem.on('click', function() {
console.log('You clicked me!');
if(currentState === true) {
console.log('It is on!');
angular.element(elem).removeAttr(attrs.src);
angular.element(elem).attr(attrs.src, "../images/First.png");
} else {
console.log('It is off!');
angular.element(elem).removeAttr(attrs.src);
angular.element(elem).attr(attrs.src, "../images/Second.png");
}
currentState = !currentState
});
}
};
});
我的目标是点击我将图像源更改为另一个。通常它应该适用于html,但我不知道为什么它在templateCache HTML上不起作用。 它必须是与AngularJS中的Directives和templateCache相关的东西,但我是这个领域的新手,我猜想我没有足够的经验。
$templateCache.put('timeline_cursor.tpl.html', '<div icon-switcher><img style=" margin-bottom:6px;cursor:pointer;" src="../images/First.png" "/></div>');
答案 0 :(得分:1)
问题出在你的iconSwitcher
指令中:
jqLite
函数removeAttr
和attr
无法识别您的属性名称 - 即。 attrs.src
throw Error
。src
。您必须将属性更改为elem.removeAttr('src', 'your/image/path');
elem.attr('src', your/image/path);
:
iconSwitcher
$templateCache
指令在iconSwitcher
内的位置以及您在$templateCache
内调用元素的方式存在冲突。因为在icon-switcher
中,您将div
属性放在img
而不是elem
标记中,指令中的div
将绑定整个$templateCache
img
1}}在iconSwicher
内而不是img
。您可以通过在img
标记中添加jqLite find
或使用link
内的var img = elem.find('img');
找到src
元素来解决此问题:
img
并更改elem
的{{1}}属性,而不是{{1}}。
Working fiddle供您参考。