17

我是 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>
4

5 回答 5

38

其他一些可能的问题:

  • 未加载包含您的指令的 Javascript 文件。如果您使用 Yeoman 生成指令并且您的 index.html 文件未修改,则可能会发生这种情况。
  • 您在 HTML 中使用camelCase元素名称而不是hyphenated。如果你的指令被调用widgetForm并且restrict'E''A',你应该使用<widget-form/>,而不是<widgetForm/>
于 2014-01-13T21:25:27.053 回答
24

您缺少该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();
                    });
        }
    };
});

演示:小提琴

于 2013-03-04T10:16:35.573 回答
2

默认情况下,当您在 angularjs 中创建指令时。如果您忽略限制属性 angularjs 将其视为属性。正如您的 html 显示的那样,您应该将返回的对象编写如下

  <body ng-app="myApp">
    <hello>
      <div id="marker"></div>
    </hello>
  </body>

并且在角度中,即使您不添加 jquery,该元素已经是一个 jQuery 对象,它将使用自己的实现调用 jQLite。所以你应该只使用

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>'
  };

});

我希望它有助于工作示例

于 2013-03-04T10:40:47.620 回答
1

@Arun 说的是正确的。但这不是强制性的。默认情况下,你的指令将是属性。

所以不要使用 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 /> 
于 2013-03-04T10:23:23.990 回答
1

不要将“指令”附加到第一个字符串参数:

.directive("someDirective", someDirective)

对我来说应该是这样的:

.directive("some", someDirective)

至少,如果你想使用它应该是:

<some>stuff</some>

查找复制粘贴错误非常糟糕。太需要找一个了... :'(

于 2016-07-02T17:37:00.540 回答