[英]Angular Directive bind function with & not passing arguments to controller
[英]Angular directive bind event and pass parameter to controller function
我有這個指令綁定和事件到輸入文件元素,並在控制器上調用一個函數
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() 不支持
selector
或eventData
。
這是一個Plunkr
這是你要找的嗎? 我試圖在這里找出更大的圖景,以了解為什么您要嘗試在指令級別中填充變量,而不僅僅是將控制器用於它的用途,而是查看下面的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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.