【问题标题】:ANGULAR: link function not being called on click in custom directiveANGULAR:在自定义指令中单击时未调用链接函数
【发布时间】:2018-08-03 00:42:45
【问题描述】:

我正在重构一个旧项目以使用自定义指令,但我已经遇到了问题。我只是想制定一个简单的指令并从那里构建。我的指令的链接函数中有一个记录器函数,它只运行一个console.log。我不确定我在这里缺少什么,我相信这很简单。这是我的指令:

'使用严格';

(function() {
    angular
        .module('sigFig')
        .directive('myDirective', myDirective);

    function myDirective(sigFigFactory) {
        var directive = {
            restrict: 'E',
            replace: 'true',
            templateUrl: 'Directives/directiveTemplate.html',
            link: link,
            compile: compile
        };
        return directive;

        function link(scope, element, attrs) {
            scope.logger = function() {
                console.log('DING!!!');
            }
        }
        function compile(scope, element, attrs) {
            console.log('I AM A COMPILE FUNCTION');
        }
    }
})();

它的 HTML 模板只是:

<button ng-click="logger()">CLICK ME</button>

我在我的 HTML 中这样称呼它:

<my-directive></my-directive>

该按钮出现并且我的编译中的 console.log 有效,但 ng-click 没有。我错过了什么?提前致谢!

【问题讨论】:

  • 解决方案是否有效?

标签: html angularjs angularjs-directive


【解决方案1】:

为指令变量添加范围:scope:{},

 function myDirective(sigFigFactory) {
        var directive = {
            scope:{},
            restrict: 'E',
            replace: 'true',
            templateUrl: 'Directives/directiveTemplate.html',
            link: link,
            compile: compile
        };
        return directive;

【讨论】:

    【解决方案2】:

    我从来没有在没有控制器的情况下创建过 Angular 应用程序。所以我很肯定这是你的问题。

    Example 的代码带有控制器。

    html:

      <body ng-app='sigFig' ng-controller='ctrl'>
        <my-directive></my-directive>
      </body>
    

    js:

    (function() {
            angular.module('sigFig', [])
            .controller('ctrl', function($scope){
                $scope.itemH = 'hahaha'
            })
            .directive('myDirective', myDirective);
    
            function myDirective() {
                return {
                    restrict: 'E',
    
                    template: '<button ng-click="logger()">{{item}}</button>',
                    link: function link(scope, element, attrs) {
                        scope.item = "Logger Click Me";
                        scope.logger = function() {
                            alert('logger')
                        }
                    }
                };
    
                function compile(scope, element, attrs) {
                    console.log('I AM A COMPILE FUNCTION');
                }
            }
        })();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 2016-11-14
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多