AngularJS - 指令不起作用
我是AngularJS newby。我正在尝试使用AngularJS指令的模板显示图像,并且点击图像我想要在图像上放置标记。我不知道为什么它不工作。AngularJS - 指令不起作用
第一个指令:
directive('hello', function() {
return {
template: '<img id="map" src="http://www.lonelyplanet.com/maps/asia/india/map_of_india.jpg" />',
link: function(scope, element, attrs) {
$('#map').click(
function(e) {
$('#marker').css('left', e.pageX).css('top', e.pageY).show();
}
);
},
};
});
的HTML代码
<hello>
<img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png" style="display: none; position: absolute;" />
</hello>
你缺少restrict : 'E'
选项,默认情况下restrict
具有价值AC
这是属性和类,你的情况你是使用该指令作为元素。
更新:基于评论
angular.module('test', []).directive('hello', function() {
return {
restrict : 'E',
template : '<div style="position: relative"><img id="map" src="http://www.lonelyplanet.com/maps/asia/india/map_of_india.jpg" /><img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png" style="display: none; position: absolute;" /></div>',
replace: true,
link : function(scope, element, attrs) {
$('#map').click(function(e) {
$('#marker').css('left', e.pageX).css('top', e.pageY)
.show();
});
}
};
});
演示:Fiddle
ok现在图像显示出来,但点击仍然没有触发 – agasthyan 2013-03-04 10:19:20
什么是#标记,它应该在哪里出现 – 2013-03-04 10:25:04
http://jsfiddle.net/arunpjohny/6XneN/2/ – 2013-03-04 10:26:57
@Arun说的是正确的。但这不是强制性的。默认情况下,ur指令将是属性。
因此而不是使用UR指令作为元素
<hello>
<img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png"style="display: none; position: absolute;" />
</hello>
尝试它作为一个属性,这样
<img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png" style="display: none; position: absolute;" hello />
默认情况下,当您在angularjs一个指令。如果你忽略restrict属性,angularjs会假定它是一个属性。作为你的HTML显示你应该写你的返回对象波纹管
<body ng-app="myApp">
<hello>
<div id="marker"></div>
</hello>
</body>
和角度的元素已经是即使你不加的jQuery它会用它自己的实现通话jQLite一个jQuery对象。所以你应该只使用
var app = angular.module('myApp', []);
app.directive('hello',function(){
var linkFn = function (scope,element,attrs){
element.bind('click',function(e){
$('#marker').css('left', e.pageX).css('top', e.pageY).show();
});
};
return {
restrict : "E",
link: linkFn,
transclude:true,
template:'<div ng-transclude><img id="map" src="http://www.lonelyplanet.com/maps/asia/india/map_of_india.jpg" /></div>'
};
});
我希望它能帮助working exmaple
一些其他可能的问题:
- 包含您的指令JavaScript文件没有被加载。如果您使用Yeoman生成您的指令,并且您的index.html文件未被修改,则会发生这种情况。
- 您正在使用camelCase元素名称在您的HTML中而不是连字符。如果您的指令被称为
widgetForm
和restrict
是'E'
或'A'
,则应该使用<widget-form/>
而不是<widgetForm/>
。
widgetForm vs小部件形式让我。 – Anthony 2014-12-03 20:15:46
谢谢!第一次犯错容易。烤肉串案件与骆驼案件也让我受益匪浅! – 2017-08-07 09:44:28
还有一件事:不要用'data'开始你的指令或属性的名字。没有错误报告,但它是保留的并且什么也不做。 – 2017-11-06 21:43:08
“指令” 不要追加到第一个字符串参数:
.directive("someDirective", someDirective)
不该得到这个对我来说:
.directive("some", someDirective)
至少,它应该是,如果你想要使用:
<some>stuff</some>
查找复制粘贴错误是可怕的。 '(
在这种情况下jsfiddle会很好 – Dogoku 2013-03-04 10:14:37