最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular ng-click not working with $compile - Stack Overflow

programmeradmin11浏览0评论

I have code similar to the below code to trigger a click event in an Angular app. Why is not the event triggering?

var app = angular.module("myApp", [])

app.directive('myTop',function($pile) {
return {
    restrict: 'E',
    template: '<div></div>',
    replace: true,
    link: function (scope, element) {
        var childElement = '<button ng-click="clickFunc()">CLICK</button>';
        element.append(childElement);
        $pile(childElement)(scope);

        scope.clickFunc = function () {
            alert('Hello, world!');
        };
    }
}
})

I have code similar to the below code to trigger a click event in an Angular app. Why is not the event triggering?

var app = angular.module("myApp", [])

app.directive('myTop',function($pile) {
return {
    restrict: 'E',
    template: '<div></div>',
    replace: true,
    link: function (scope, element) {
        var childElement = '<button ng-click="clickFunc()">CLICK</button>';
        element.append(childElement);
        $pile(childElement)(scope);

        scope.clickFunc = function () {
            alert('Hello, world!');
        };
    }
}
})
Share Improve this question edited Dec 10, 2015 at 9:26 Shashank Agrawal 25.8k11 gold badges96 silver badges125 bronze badges asked Dec 10, 2015 at 2:28 freddy83freddy83 631 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Change your pile statement like this:

$pile(element.contents())(scope);

You were passing a DOM string childElement which is really not a DOM element instead it is a string. But the $pile needs the DOM element(s) to actually pile the content.

var app = angular.module("myapp", []);

app.directive('myTop', ['$pile',
  function($pile) {
    return {
      restrict: 'E',
      template: '<div></div>',
      replace: true,
      link: function(scope, element) {
        var childElement = '<button ng-click="clickFunc()">CLICK</button>';
        element.append(childElement);
        $pile(element.contents())(scope);

        scope.clickFunc = function() {
          alert('Hello, world!');
        };
      }
    }
  }
])
<html>

<body ng-app="myapp">
  <script src="https://ajax.googleapis./ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <my-top></my-top>
</body>

</html>

发布评论

评论列表(0)

  1. 暂无评论