【问题标题】:Angular directive bind event and pass parameter to controller functionAngular 指令绑定事件并将参数传递给控制器​​函数
【发布时间】:2018-02-22 14:37:19
【问题描述】:

我有这个指令绑定和事件到输入文件元素,并在控制器上调用一个函数

appFuncionario.directive('onFileChange', function () {
   return {
      restrict: 'A',
      link: function (scope, element, attrs) {

         var onChangeHandler = scope.$eval(attrs.onFileChange);
         //this is where I want to send the parameter
         element.on('change', onChangeHandler);

         element.on('$destroy', function () {
            element.off();
         });

      }
   };
});


<input ng-show="campo.codTipoCampo === 'InputFile'" id="{{campo.id}}" type="file" campo="{{campo}}" on-file-change="uploadFile" />

 //Function in the controller - this is where I want to get a parameter from the directive
 $scope.uploadFile = function (parameter) {

        //do something here
};

我需要将指令所在对象的参数传递给指令在更改事件上执行的函数。

我知道我可以在元素上使用类似 campo="{{campo}}" 的东西,并在指令上像这样 attrs.campo 那样捕获它,但我不知道如何进行此绑定

element.on('change', onChangeHandler);

传递参数 - 我总是得到这个错误

jqLit​​e#on() 不支持selector 或eventData。

这是Plunkr

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    这就是你要找的吗?我试图在这里找出更大的图景,为什么您要尝试在指令级别中填充变量,而不仅仅是将控制器用于其预期用途,而是查看下面的Fiddle 和 lmk如果这就是你要找的东西。

    // Code goes here
    
    var app = angular.module('fiddle', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.teste = function(campo) {
        alert("Campo: " + campo);
      };
      
    });
    
    app.directive('onFileChange', function() {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
    
          var onChangeHandler = scope.$eval(attrs.onFileChange);
          element.on('change', function() {
          	onChangeHandler(attrs.campo);
          });
    
          element.on('$destroy', function() {
            element.off();
          });
    
        }
      };
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="fiddle">
      <div ng-controller="MainCtrl">
        <!-- 
          Attribute campo is the variable stuffed into the 
          controller function via the directive on change event
        -->
        <input type="file" campo="{{'I did it!'}}" on-file-change="teste" />
      </div>
    </div>

    【讨论】:

    • 投反对票的人想解释他们投反对票的原因吗?将不胜感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多