我的Angular js指令不适用于append div



我正在学习angular。因此,试图构建我的第一个与DOM交互但不起作用的指令。请告诉我代码中遗漏了什么。这是代码。

<div class="main" ng-app="myApp">
<button data-ng-click="submit()" my-directive>click</button>
</div>
app.module('myApp', []);
app.directive('myDirective',function(){
     return function(scope, element, attrs){
          element.click(function(){
               alert('hello');
               element.parent().find('.main').append('<div>Some text</div>');
           })
      }
})

我的js小提琴链接https://jsfiddle.net/tridip/2fooy06c/

您缺少"链接"属性:

app.directive('myDirective',function(){
     return {
        link:  function(scope, element, attrs){
          element.click(function(){
               alert('hello');
               element.parent().find('.main').append('<div>Some text</div>');
           })
           }
      }
})

请按以下方式更改您的代码,它就会工作。元素中没有click这样的函数。请检查此文档https://docs.angularjs.org/api/ng/function/angular.element此处

另外,不要忘记在指令中包含typelink属性。Type用于指示您正在创建的指令类型。有关的更多详细信息,请参阅此处

app.directive('myDirective',function(){
 return {
   type: "A",
   link: function(scope, element, attrs) {
     element.on("click", function() {
       alert('hello');
       element.parent().append('<div>Some text</div>');
     });
   }
 }
});

参考这个plnkr示例https://plnkr.co/edit/CYyOKzjR1kBR3U0tG3jv?p=preview有关更多详细信息,

element.click不是一个函数。您需要使用.bind 附加事件

var myApp = angular.module('myApp',[]);
myApp.directive('myDirective',function(){
     return {
        link:  function(scope, element, attrs){
          element.bind('click',function(){
               alert('hello');
               element.parent().append('<div>Some text</div>');
           })
           }
      }
})

演示:http://jsfiddle.net/Lvc0u55v/2018/

您需要绑定点击函数。参见演示

app.directive('myDirective', function () {
return {
    link: function ($scope, element, attrs) {
        element.bind('click', function () {
           alert('hello');
           element.parent().append('<div>Some text</div>');
        });
    }
  };
});

相关内容

最新更新