角指令绑定事件并将参数传递给控制器函数



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

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);

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

jqlite#on((不支持 selectoreventData

这是一个plunkr

这是您想要的吗?我试图在这里弄清楚为什么要在指令级别中塞入变量,而不仅仅是使用控制器的目的,但请查看下面的小提琴和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>

最新更新