Angularjs Custom Directive ng-click not working

前端 未结 2 1908
予麋鹿
予麋鹿 2021-02-20 04:21

i\'ve created a custom directive in angularjs:

directives.directive(\'myTop\',function($compile) {
return {
    restrict: \'E\',
    templateUrl: \'views/header.         


        
相关标签:
2条回答
  • 2021-02-20 04:55

    You'll need to add a link function to the directive definition for this to work. So basically,

    var app = angular.module("myApp", [])
    
    app.directive('myTop',function() {
    return {
        restrict: 'E',
        template: '<button ng-click="clickFunc()">CLICK</button>',
        link: function (scope) {
            scope.clickFunc = function () {
                alert('Hello, world!');
            };
        }
    }
    })
    

    And the html:

    <div ng-app="myApp">
        <my-top></my-top>
    </div>
    

    And here's the fiddle: http://jsfiddle.net/4otpd8ah/

    0 讨论(0)
  • 2021-02-20 05:11

    Either use link as answered by @Ashesh or just simply add scope. If you set scope false you will not have isolated scope and click will work on directive.

    directives.directive('myTop',function($compile) {
    return {
       restrict: 'EA',
       scope: false,
       templateUrl: 'views/header.html',
      }
    })
    
    0 讨论(0)
提交回复
热议问题