如何使用元素名称调用指令?

How to invoke a directive by using element name?

我有一个 angular 指令:

app.directive('myDirective', function()
{
  return{
    restrict: 'AE',
    scope: {
        myCustomer: "&"
    },
    require: 'ngModel',
    link: function(scope, element, attr, ngModel){
        var oldVal;
        function fromUser(value){
            scope.myCustomer()(value, oldVal);
            oldVal = value;
            return value;
        }

        function toUser(value){
            return value;
        }

        ngModel.$parsers.push(fromUser);

        ngModel.$formatters.push(toUser);
    }
  }
}

目前我通过使用属性名调用这个控制器并将它绑定到一个函数:

 <input type="text" my-directive="showInput" ng-model="user.name">

它工作正常,但我想要的是使用元素名称,如下所示:

<my-directive>

问题是我不知道如何像处理属性那样绑定到函数。

您需要在指令定义中将 'restrict' 设置为 'E',例如:

        bindToController: true,
        controller: 'YourController',
        controllerAs: 'vm',
        restrict: 'E', //<----this is what you want
        templateUrl: 'template.html'

你必须通过 restrict: 'E' 在指令选项

angular.module("image-management")
    .directive('myDirective', ($modal) => {

        return {
            restrict: 'E',
            scope:{
              showInput: '&'  
            },
            template: '',
            link: function(){}
})   

    <my-directive showInput="showInput" ></my-directive>

<my-directive some-function="someFunction"></my-directive>

然后在你的指令 link 函数中,它可以通过 attr

访问
link: function(scope, element, attr, ngModel){
    // Your logic...
    attr.someFunction();
}

正如@sumair 回答的那样,您可以这样做:

<my-directive showInput="showInput" ></my-directive>

但是,如果你真的只想使用

<my-directive>

并且你的指令不需要有一个独立的作用域,你可以只保留指令定义的作用域 属性 并直接从继承的作用域引用你的 showInput 函数,如下所示:

app.directive('myDirective', function()
{
  return{
    restrict: 'AE',
    /*scope: { ////// remove this part //////
        myCustomer: "&"
    },*/
    require: 'ngModel',
    link: function(scope, element, attr, ngModel){
        var oldVal;
        function fromUser(value){
            scope.showInput()(value, oldVal);
            oldVal = value;
            return value;
        }

        function toUser(value){
            return value;
        }

        ngModel.$parsers.push(fromUser);

        ngModel.$formatters.push(toUser);
    }
  }
}