【问题标题】:How to call my own function inside an Angular Directive?如何在 Angular 指令中调用我自己的函数?
【发布时间】:2015-02-09 21:32:02
【问题描述】:

我想在我的角度指令中调用“myFunc()”,我该怎么做?

myApp.directive("test", function () {
 return {
   restrict: 'A',
     template: "<div class='box'></div>",
     myFunc: function() {
                console.log('myFunc');
       },
     link: function ($scope, element, attrs) {

         element.bind('click', function () {
               myFunc(); //<------------- doesn't work
       });
     }
    } // of return
});

【问题讨论】:

  • afaik 这是不可能的,我认为你应该使用 scope : '&' 并将函数放在控制器中,但可能你只知道 :)

标签: javascript angularjs angular-directive


【解决方案1】:

您不能在调用指令中将函数定义为返回值的属性。它要么需要在您返回之前定义:

myApp.directive('test', function() {
    var myFunc = function() {
        console.log('myFunc');
    };

    return {
        restrict: 'A',
        template: '<div class="box"></div>',
        link: function($scope, element, attrs) {
            element.bind('click', myFunc);
        }
    };
};

或者在 link 函数中使用相同的方式。

【讨论】:

    【解决方案2】:

    只是玩玩:)

    var app = angular.module('myApp', []);
    app.controller('MainController',function() {
    
    });
    app.directive('one', function() {
        return angular.extend({}, app.directive, {myfunct:function(){
                    alert('hello');
        }});
    });
    app.directive('two', function(oneDirective) {
        return {
            link:function($scope,$element){
                console.log(oneDirective[0].myfunct)
                $element.on('click',oneDirective[0].myfunct);
            }
        };
    });
    

    【讨论】:

      【解决方案3】:

      或者使用方法绑定“&”:

      app.directive('myDir', function() {
          return {
              scope: {
                  callback: "&"  
              },
              link:function($scope,$element){
      
                   element.bind('click', function () {
                     $scope.evalAsync(function() {
                        $scope.callback({param1: value, param2: value2});
                     })
                   });
              }
          };
      });
      

      用法:

      <my-dir callback="myControllerMethod(param1, param2)"></my-dir>
      

      【讨论】:

        猜你喜欢
        • 2015-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多